Localization in external class libraries in ASP.NET Core

I have two projects:

  • MyWebApp - Basic ASP.NET Web Interface
  • MyServices is a .NET Core class library that contains useful services for the project above

How to add localization IStringLocalizer

to MyServices ? Where should the files be located .resx

?

+3


source to share


2 answers


One typical solution for your MyServices build is to return resource keys (instead of returning the actual resources to be displayed on screen). You can have a .resx file as part of MyWebApp and have resource values ​​for each resource key. This way your MyService can be used by various UI applications, each with their own resource views.

Another approach would be to keep the .resx file as part of MyService itself. MyWebApp can load another assembly and read the resource file from that.

Another option is to save the resources as a new assembly and load it again from MyWebApp.

Check out the following SO answers to get more details on how to access .resx files from another assembly -



How can I read the embedded .resx in another assembly

Accessing string resources from embedded .resx in dll?

How can I access the .resx of another assembly?

+3


source


You can save the .resx files in the MyServices project and create a method to retrieve resources based on keys. To access IStringLocalizer from MyServices , you need to install Microsoft.Extensions.Localization.Abstractions

nuget.

Basically localization config should stay on MyWebApp (launch class), but in MyServices you need to add this nuget to use IStringLocalizer and create a method like GetResourceValueByKey (key). This method can be called from anywhere where the MyServices project will reference .



using Microsoft.Extensions.Localization;

namespace GlobalizationLibrary {Public class SharedResource: ISharedResource {private readonly IStringLocalizer _localizer;

public SharedResource(IStringLocalizer<SharedResources> localizer) { _localizer = localizer; } public string GetResourceValueByKey(string resourceKey) { return _localizer[resourceKey]; } }}

0


source







All Articles