Localization in external class libraries in ASP.NET Core

让人想犯罪 __ 提交于 2020-07-17 09:34:35

问题


I have two projects:

  • MyWebApp - ASP.NET Core Web API
  • MyServices - .NET Core class library, which contains helpful services for project above

How can I add localization with IStringLocalizer to MyServices? Where must be .resx files located?


回答1:


This is how I solved it. Thanks to Popa Andrei answer for directing me to the right place.

Class Library

Solution -> right click -> Add -> New Project ... -> .Net standard -> Class Library -> I used the name ResourceLibrary

ResourceLibrary
|- Resources
|----- SharedResource.resx
|----- SharedResource.he.resx
|- SharedResource.cs

SharedResource.cs code:

using Microsoft.Extensions.Localization;

namespace ResourceLibrary
{
    public interface ISharedResource
    {
    }
    public class SharedResource : ISharedResource
    {
        private readonly IStringLocalizer _localizer;

        public SharedResource(IStringLocalizer<SharedResource> localizer)
        {
            _localizer = localizer;
        }

        public string this[string index]
        {
            get
            {
                return _localizer[index];
            }
        }
    }
}

web application

Right click on webapp project -> Add -> Reference ... -> Check Resource Library

In your webapp startup.cs:

using ResourceLibrary;
...

public void ConfigureServices(IServiceCollection services) {
    ...
    services.AddLocalization(o => { o.ResourcesPath = "Resources"; });

    services.Configure<RequestLocalizationOptions>(options =>
            {
                CultureInfo[] supportedCultures = new[]
                {
                    new CultureInfo("en"),
                    new CultureInfo("he")
                };

                options.DefaultRequestCulture = new RequestCulture("en");
                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;
             });
     ...
     }

     public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
        ...
        app.UseRequestLocalization(); //before app.UseMvc()
        ...
        }

Example use in controller:

 using ResourceLibrary;
 ...

 public class ExampleController : Controller
    {
    private readonly IStringLocalizer<SharedResource> _sharedLocalizer;
    public EmailsController(IStringLocalizer<SharedResource> sharedLocalizer)
    {
        _sharedLocalizer = sharedLocalizer;
    }

    [HttpGet]
    public string Get()
    {
        return _sharedLocalizer["StringToTranslate"];
    }

View example:

@using Microsoft.AspNetCore.Mvc.Localization
@inject IHtmlLocalizer<ResourceLibrary.SharedResource> SharedLocalizer

<p>@SharedLocalizer["StringToTranslate"]</p>



回答2:


One typical solution is for your MyServices assembly to return resource keys (instead of returning the actual resources to be displayed on screen). You can have the .resx file as part of MyWebApp and have resource values for each resource key. This way, your MyService can be utilized by various UI apps each of which have their own resource representations.

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

Yet another option would be to keep the resources as a new assembly, and again load it from MyWebApp.

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

How can I read embedded .resx in different assembly

Access strings resources from embedded .resx in dll?

How to access another assembly's .resx?




回答3:


You can store the .resx files on MyServices project and create a method for retrieving the resources based on keys. In order to access the IStringLocalizer from MyServices you have to install Microsoft.Extensions.Localization.Abstractions nuget.

Basically localization configurations have to remain on MyWebApp (Startup class), but on MyServices you have to add that nuget for using IStringLocalizer and create a method like GetResourceValueByKey(key). This method can be called from wherever MyServices project will be referenced.

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]; } }}


来源:https://stackoverflow.com/questions/45167350/localization-in-external-class-libraries-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!