Files
EnvelopeGenerator/EnvelopeGenerator.ReceiverUI/Services/CultureService.cs
TekH c93a056ca5 Add CultureService and localization support
Added a new `CultureService` to manage application culture and
localization. The service supports retrieving and setting the
application culture, storing it in `localStorage`, and initializing
it based on stored values, browser settings, or a default fallback.

Registered `CultureService` in the dependency injection container
and added localization support in `Program.cs` using
`builder.Services.AddLocalization()`.
2026-06-17 16:54:40 +02:00

75 lines
2.1 KiB
C#

using System.Globalization;
using Microsoft.JSInterop;
namespace EnvelopeGenerator.ReceiverUI.Services;
/// <summary>
/// Service for managing application culture/localization.
/// </summary>
public class CultureService
{
private readonly IJSRuntime _jsRuntime;
private const string CULTURE_KEY = "AppCulture";
public CultureService(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
/// <summary>
/// Gets the list of supported cultures.
/// </summary>
public static CultureInfo[] SupportedCultures { get; } = new[]
{
new CultureInfo("de-DE"),
new CultureInfo("en-US"),
new CultureInfo("fr-FR")
};
/// <summary>
/// Sets the application culture and stores it in localStorage.
/// </summary>
public async Task SetCultureAsync(string culture)
{
if (!SupportedCultures.Any(c => c.Name == culture))
throw new ArgumentException($"Culture '{culture}' is not supported.", nameof(culture));
await _jsRuntime.InvokeVoidAsync("localStorage.setItem", CULTURE_KEY, culture);
}
/// <summary>
/// Gets the stored culture from localStorage.
/// </summary>
public async Task<string?> GetCultureAsync()
{
try
{
return await _jsRuntime.InvokeAsync<string?>("localStorage.getItem", CULTURE_KEY);
}
catch
{
return null;
}
}
/// <summary>
/// Initializes the culture from localStorage or browser settings.
/// </summary>
public async Task<CultureInfo> InitializeCultureAsync()
{
var storedCulture = await GetCultureAsync();
if (!string.IsNullOrEmpty(storedCulture) &&
SupportedCultures.Any(c => c.Name == storedCulture))
{
return new CultureInfo(storedCulture);
}
// Fallback to browser culture or default
var browserCulture = CultureInfo.CurrentCulture.Name;
var matchedCulture = SupportedCultures.FirstOrDefault(c => c.Name == browserCulture);
return matchedCulture ?? SupportedCultures[0]; // Default to German
}
}