Reputation: 25
I doing localization for one site.
But I found that I need to define a new ".resx" per View or Controller.
Is there a way to set up a global file for each language instead of creating one file per (number of Localization) * views?
Upvotes: 1
Views: 1554
Reputation: 924
The trick is to create a wrapper for IStringLocalizer
. Here's what I use:
public class Localizer
{
private readonly IStringLocalizer localizer;
public Localizer(IStringLocalizerFactory fact)
{
var type = typeof(SharedResource);
var assembly = new AssemblyName(type.GetTypeInfo().Assembly.FullName).Name;
localizer = fact.Create(nameof(SharedResource), assembly);
}
public LocalizedString this[string key] => localizer[key];
public LocalizedString this[string key, params object[] arguments] => localizer[key, arguments];
}
And then inject that into your controllers and views. Based on this guy's blog post: https://medium.com/@flouss/asp-net-core-localization-one-resx-to-rule-them-all-de5c07692fa4
Upvotes: 1
Reputation: 127
From the official documentation "There's no option to use a global shared resource file.".
You can only use global resource file for DataAnnotations localization:
services.AddMvc().AddDataAnnotationsLocalization(options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
{
return factory.Create(typeof(ErrorMessage));
};
});
where ErrorMessage is just an empty class.
Upvotes: 1