Share localization resources between an ASP.NET MVC app and a class library in .NET

243 Views Asked by At

I have an ASP.NET MVC app with localized resources. I want to use a class library inside the app, and I want to be able to share resources from class library in my ASP.NET MVC app, and from the ASP.NET MVC app inside class library.

What is the suggestion for this?

1

There are 1 best solutions below

0
Mehdi Mowlavi On

Consider we have a class library as below (ClassLibAssembly):

namespace MyCustomResourceClassLib;
public class LogGenerator
{
    public IStringLocalizer<LogGenerator> _localizer;
    public LogGenerator(IStringLocalizer<LogGenerator> localizer)
    {
        _localizer=localizer;
    }
    public string ReturnCulturizedString() {
        return _localizer["Log Generator"];
    }
    public void PrintCulturizedString() {
        Console.WriteLine(_localizer["Hello World"]);
    }
}

and also consider we have an MVC App with localization services and middleware added (Main Assembly). Consider following simple api where localizer is an instance of IStringLocalizer<LogGenerator>:

app.MapGet("/logs", () => localizer["Hello World"]);

Question 1- We have resource .resx file in ClassLibAssembly and want it do localizations: Answer: Simply Add following attributes if they are required (The first one specify the location which have resource file inside the class library and the second attribute is NeutralResourcesLanguage in case of having a default culture):

[assembly: ResourceLocation("Resources")]
[assembly: NeutralResourcesLanguage("es-MX",UltimateResourceFallbackLocation.Satellite)]

in this case simply define localizer as below in MVC App:

var localizer = app.Services.GetRequiredService<IStringLocalizer<LogGenerator>>();

In this case the resource file exist in the class library inside the location you specify with the attribute (for example Resources Folder)

Question 2- You want to add your custom localized resources in Main Assembly (MVC App) In this case using localizer as above do not work but if you use String Localizer Factory as below, it works as expected. First you need to change Root namespace in class library to same as MVC App. For example:

[assembly:RootNamespace("MVCLocalization")]

Then create an instance of IString Localizer using factory as below:

var factory=app.Services.GetRequiredService<IStringLocalizerFactory>();
var localizer=factory.Create("MVCLocalization.Resources.MyCustomResourceClassLib.LogGenerator",Assembly.GetExecutingAssembly().FullName);

In this case only dot notations works with following resx file and the folder path notation do not works for resource files:

MVCLocalization.Resources.MyCustomResourceClassLib.LogGenerator.resx

In this case as already mentioned the resource file exist in main assembly (MVC App)