Localization in external class libraries in ASP.NET Core

Yurii N. picture Yurii N. · Jul 18, 2017 · Viewed 9.1k times · Source

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?

Answer

Shiran Dror picture Shiran Dror · Jun 3, 2018

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>