In .net 8 razor, how would I go about having a shared localization resource in my project?
Currently, I have the following layout:
This works for the index page, but I also want resources from RShared.resx (poorly named, but this is an example).
_ViewImports:
@using SE.Web
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
@namespace SE.Web.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
program.cs
builder.Services.AddLocalization(options => options.ResourcesPath = "LocalizationResources");
builder.Services.AddRazorPages(options =>
{
options.Conventions.Add(new CustomRouteModelConvention());
}).AddViewLocalization();
how would I go about having a shared localization resource in my project
Try to use the IStringLocalizerFactory interface to create IStringLocalizer instances, then register the Service with the DI system, below is a demo, you can refer to it.
public class RSharedResources
{
}
2.Add a new folder to the root of the project named Services. Add a C# class file to the folder named RSharedService.cs with the following code:
public class RSharedService
{
private readonly IStringLocalizer localizer;
public RSharedService(IStringLocalizerFactory factory)
{
var assemblyName = new AssemblyName(typeof(RSharedResources).GetTypeInfo().Assembly.FullName);
localizer = factory.Create(nameof(RSharedResources), assemblyName.Name);
}
public string Get(string key)
{
return localizer[key];
}
}
3.Register the RSharedService in Program.cs:
builder.Services.AddSingleton<RSharedService>();
4.Add a resource file to the Resources folder named RSharedResources.en.resx.
Greeting Hello afternoon!
5.Inject the RSharedService into the index page:
@using yourprojectname.Services
@inject RSharedService localizer
@localizer.Get("Greeting")
?culture=en
Structure:
result: