I have two projects:
How can I add localization with IStringLocalizer
to MyServices? Where must be .resx
files located?
This is how I solved it. Thanks to Popa Andrei answer for directing me to the right place.
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];
}
}
}
}
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()
...
}
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"];
}
@using Microsoft.AspNetCore.Mvc.Localization
@inject IHtmlLocalizer<ResourceLibrary.SharedResource> SharedLocalizer
<p>@SharedLocalizer["StringToTranslate"]</p>