In .NET core, doing i18n is more easy than .NET Framework in my opinions, just give appropriate setting, then you can easily assign i18n string to anyplace you want.
Let's see how it work.
Make sure your ResourcesPath set to right path.
The "Message" is my resource name, you can DI multi Localizer if you have not only one resource group.
If you wanna get a localization string for enum, it was easy too, for example your enum called "WeatherSummary".
It was very simple, don't need add custom thing like LocalizedDescriptionAttribute for enum i18n in .NET Framework.
You can check my demo code on github .NET-Core-Localization-and-Enum
Hope you enjoy it.
Let's see how it work.
1.Add resource file
Usually I will put my resource file in [Resources] folder, remember put cultureInfo name on resx file like this.
2.Setup Startup.cs
Add following code (depending how many language you support) into your IServiceCollection//set Support Cultures and default
services.Configure(options =>
{
var supportedCultures = new[]{
new CultureInfo("en-US"),
new CultureInfo("zh-TW"),
new CultureInfo("ja-JP")
};
options.DefaultRequestCulture = new RequestCulture("en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
//set resource path
services.AddLocalization(options => options.ResourcesPath = "Resources");
Make sure your ResourcesPath set to right path.
3.DI Localizer
Since we are using .NET Core, so we need to DI our Localizer before we using it, for example if you are use it on a controller.private readonly IStringLocalizer _localizer;
public YourController(IStringLocalizerFactory factory)
{
_localizer = factory.Create("Message", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
}
The "Message" is my resource name, you can DI multi Localizer if you have not only one resource group.
4.Usage
Here is the content of my resource, the usage for Localizer is easy, just use it like a dictionary.var str = _localizer["Cool"];
If you wanna get a localization string for enum, it was easy too, for example your enum called "WeatherSummary".
var str = _localizer[WeatherSummary.Cool.ToString()];
It was very simple, don't need add custom thing like LocalizedDescriptionAttribute for enum i18n in .NET Framework.
You can check my demo code on github .NET-Core-Localization-and-Enum
Hope you enjoy it.
No comments:
Post a Comment