Search code examples
asp.netasp.net-corerazorlocalization

Shared localization resource file in Razor


In .net 8 razor, how would I go about having a shared localization resource in my project?

Currently, I have the following layout:

enter image description here

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();

Solution

  • 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.

    1. Add a new class file to the Resources folder(your LocalizationResources folder) named RSharedResources. It is an empty class.
     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")
    
    1. Pass the culture query parameter with the value set to de : ?culture=en

    Structure:

    enter image description here

    result:

    enter image description here