我正在使用
IStringLoclizer
方法和包含键值对的 resx
文件来本地化我的应用程序,如 文档中所述。
我刚刚发现:
一方面,
.resx
文件不区分大小写(存储密钥Firstname
和
FirstName
将引发密钥已存在的错误)。另一方面,当我想检索键时,它
IS区分大小写(如果键Firstname
存在并且我想获取
FirstName
的值,则
IStringLoclizer
不会检索该值 -从键值对的角度来看这是有意义的!)。有没有办法覆盖
IStringLocalizer
getters,以实现一些逻辑(例如,将所有键更改为小写,并按小写搜索任何键)?有效解决方案的关键是避免更改
.resx
文件中的所有键以及我调用
IStringLocalizer
的位置。
编辑
我发现了 ResourceManager.IgnoreCase
here,但我不清楚如何访问资源管理器 - 可能这必须以某种方式在
Startup.cs
中完成?
ResourceManagerStringLocalizerFactory
来实现。
public class CaseInsensitiveResourceManagerStringLocalizerFactory : ResourceManagerStringLocalizerFactory
{
public CaseInsensitiveResourceManagerStringLocalizerFactory(IOptions<LocalizationOptions> localizationOptions, ILoggerFactory loggerFactory) : base(localizationOptions, loggerFactory)
{
}
//unfortunately we need to use reflection to the the ResourceManager as the field is private
private readonly FieldInfo _field = typeof(ResourceManagerStringLocalizer).GetField("_resourceManager", BindingFlags.NonPublic | BindingFlags.Instance);
//override this method to access the resource manager at the time it is created
protected override ResourceManagerStringLocalizer CreateResourceManagerStringLocalizer(Assembly assembly, string baseName)
{
//call the base method to get the localizer, I would like to override this implementation but the fields used in the construction are private
var localizer = base.CreateResourceManagerStringLocalizer(assembly, baseName);
if (_field == null) return localizer;
//set the resource manager to ignore case
if (_field.GetValue(localizer) is ResourceManager resourceManager) resourceManager.IgnoreCase = true;
return localizer;
}
}
您需要在添加本地化之前注册工厂。
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IStringLocalizerFactory, CaseInsensitiveResourceManagerStringLocalizerFactory>();
services.AddLocalization(options => { options.ResourcesPath = "Resources"; });
//other service configurations....
}
我希望将来这些类能够变得更具可扩展性。
ResourceManagerStringLocalizerFactory
和
ResourceManagerStringLocalizer
中的私有字段都需要反射。