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();
2
Answers
Using the answer from Qing Guo, here was the final over-engineered version:
ServicesLocalizerService
ResourcesRSharedResources (same directory as shared resx file)
ResourcesLocalizerResource (same directory as shared resx files)
Program.cs
Potential uses in razor pages:
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.
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:
3.Register the RSharedService in Program.cs:
4.Add a resource file to the Resources folder named RSharedResources.en.resx.
5.Inject the RSharedService into the index page:
?culture=en
Structure:
result: