On my ASP.NET Core 3.1 website I'm trying to generate alternate links for different supported languages. These links are stored in resources. I'm using IStringLocalizer<> as a dependency in my class to get the translations. There used to be an extension method .WithCulture() that allowed string localizer to lookup in different culture. However this is marked obsolete (and removed in .NET 5).
What is the best approach to load single key from multiple available cultures? I'm currently "hacking" it using this approach
var originalCulture = Thread.CurrentThread.CurrentUICulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(cultureCode);
var localized = localizer[myKey];
Thread.CurrentThread.CurrentUICulture = originalCulture;
for each supported language. However this simply doesn't seem right to me.
Is there a better approach?
Also I think there is some kind of race condition as I encountered some texts being randomly rendered in incorrect culture - because I¨M changing some global state..
For future searchers, this Microsoft page, in a very roundabout way, describes how to do this.
The key is to use ResourceManager. Something like this:
var rm = new System.Resources.ResourceManager(typeof(Common));
CultureInfo = CultureInfo.GetCultureInfo("es");
var localizedString = rm.GetString("All", ci);
Where Common is the name of your resource file, and "All" is the key/name for the string you wish to retrieve. In this example, it's using the es (spanish) culture.
You may need a using System.Globalization; in your code, if you don't have it already.
I've been doing this successfully from .NET 6 through .NET 9, as of this writing.
Happy localizing!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With