Changing the language of an IStringLocalizer

Viewed 5168

I am attempting to dynamically set the language of an IStringLocalizer at run time. The only available method that seems to do this is IStringLocalizer.WithCulture. However, attempting to use it results in a deprecation warning.

public IStringLocalizer GetLocalizer(string locale) {
    this.localizerFactory.Create(typeof(CommonResources)).WithCulture(new CultureInfo(locale));
}

I am not using ASP, I am doing this in an IHostedService that handles user interaction from another source (various web chat APIs). This service needs to conform to the language set for the chat server or channel by the admins (stored in database).

What is the correct, current way of setting the language of an IStringLocalizer? Should I use another class entirely?

2 Answers

This should do it. You need to set CultureInfo.CurrentUICulture to the culture you want before getting the string value.

    private string GetStringValue(string stringName, string culture)
    {
        var specifiedCulture = new CultureInfo(culture);
        CultureInfo.CurrentCulture = specifiedCulture;
        CultureInfo.CurrentUICulture = specifiedCulture;
        var options = Options.Create(new LocalizationOptions { ResourcesPath = "Resources" });
        var factory = new ResourceManagerStringLocalizerFactory(options, new LoggerFactory());
        var localizer = new StringLocalizer<RecipeController>(factory);
        return localizer[stringName];
    }

If you have an instance of IStringLocalizer you can use it instead of creating a new one.

you may write your own culture middleware which can set the culture based on the user or maybe using the Http Header Accept-Language

app.UseRequestLocalization(roptions =>
        {
            IList<CultureInfo> supportedCultures = new List<CultureInfo>
            {
                new CultureInfo("en-US"),
                new CultureInfo("fr"),
            };
            roptions.DefaultRequestCulture = new RequestCulture("en-US");
            roptions.SupportedCultures = supportedCultures;
            roptions.SupportedUICultures = supportedCultures;
            roptions.RequestCultureProviders.Add(new YourCustomCultureProvider());
        });

Sample Middleware

public class YourCustomCultureProvider : RequestCultureProvider
{
    public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
    {
        if (httpContext == null)
            throw new ArgumentNullException(nameof(httpContext));


        var culture = //Some Logic

        if (string.IsNullOrEmpty(culture))
        {
            // No values specified for either so no match
            return Task.FromResult((ProviderCultureResult)null);
        }

        var requestCulture = new ProviderCultureResult(culture);

        return Task.FromResult(requestCulture);
    }
}

Refer this link if it could help you - https://joonasw.net/view/aspnet-core-localization-deep-dive

Related