在 .net 8 razor 中,我将如何在我的项目中拥有共享本地化资源?
目前,我有以下布局:
这适用于索引页,但我还需要来自 RShared.resx 的资源(名称不好,但这是一个示例)。
_查看进口:
@using SE.Web
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
@namespace SE.Web.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
程序.cs
builder.Services.AddLocalization(options => options.ResourcesPath = "LocalizationResources");
builder.Services.AddRazorPages(options =>
{
options.Conventions.Add(new CustomRouteModelConvention());
}).AddViewLocalization();
我将如何在我的应用程序中拥有共享的本地化资源 项目
尝试使用IStringLocalizerFactory接口创建IStringLocalizer实例,然后将Service注册到DI系统中,下面是一个demo,大家可以参考一下。
public class RSharedResources
{
}
2.在项目根目录添加一个名为Services的新文件夹。使用以下代码将 C# 类文件添加到名为 RSharedService.cs 的文件夹中:
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.在Program.cs中注册RSharedService:
builder.Services.AddSingleton<RSharedService>();
4.在Resources文件夹中添加一个名为RSharedResources.de.resx的资源文件。
Localisation Lokalisierung
Privacy rivatsphäre
5.将RSharedService注入到索引页:
@using yourprojectname.Services
@inject RSharedService localizer
@localizer.Get("Localisation")
@localizer.Get("Privacy")
?culture=de
结构:
结果: