[Asp.net 5] Localization-resx资源文件的管理

时间:2022-09-14 17:41:13

上一篇博文地址:[Asp.net 5] Localization-简单易用的本地化-全球化信息

本文继续介绍asp.net 5多语言。今天重点讲的是多语言的resx文件。涉及到的工程有:Microsoft.Framework.Localization.Abstractions以及Microsoft.Framework.Localization。他们之间的类结构如下如所示:

[Asp.net 5] Localization-resx资源文件的管理

  • Abstractions包中,包含了定义在工程Microsoft.Framework.Localization.Abstractions的大部分类和接口
  • Localization包中,包含了定义在工程Microsoft.Framework.Localization中的大部分类和接口

Microsoft.Framework.Localization.Abstractions

该工程定义了本地化(全球化)的基本接口,以及一些抽象类。

  • LocalizedString 封装name、value等属性的结构体,用于表示本地化寻找的结果
  • IStringLocalizer 本地化访问的基本接口,通过方法或者属性(通过扩展方法,使得方法和属性调用一套逻辑)获得LocalizedString结构体对象;本解决方案中,对资源文件就是该接口的 实例操作的
  • IStringLocalizer<T> 本接口中未定义任何方法,是IStringLocalizer 的泛型版本
  • StringLocalizer<TResourceSource>,该类是IStringLocalizer<T> 的实现类,内部分装IStringLocalizer 接口。使用了代理模式(前面我们介绍的配置文件、以及依赖注入都使用了该模式),所有方法都是内部IStringLocalizer对象的封装。该类的构造函数是IStringLocalizerFactory接口。
  • IStringLocalizerFactory接口:根据不同的Type类型创建不同的IStringLocalizer对象
public struct LocalizedString
{
public LocalizedString([NotNull] string name, [NotNull] string value)
: this(name, value, resourceNotFound: false)
{ } public LocalizedString([NotNull] string name, [NotNull] string value, bool resourceNotFound)
{
Name = name;
Value = value;
ResourceNotFound = resourceNotFound;
} public static implicit operator string (LocalizedString localizedString)
{
return localizedString.Value;
} public string Name { get; } public string Value { get; } public bool ResourceNotFound { get; } public override string ToString() => Value;
}

LocalizedString

    public interface IStringLocalizer : IEnumerable<LocalizedString>
{
LocalizedString this[string name] { get; } LocalizedString this[string name, params object[] arguments] { get; } IStringLocalizer WithCulture(CultureInfo culture);
}

IStringLocalizer

public interface IStringLocalizer<T> : IStringLocalizer
{ } public class StringLocalizer<TResourceSource> : IStringLocalizer<TResourceSource>
{
private IStringLocalizer _localizer; public StringLocalizer([NotNull] IStringLocalizerFactory factory)
{
_localizer = factory.Create(typeof(TResourceSource));
} public virtual IStringLocalizer WithCulture(CultureInfo culture) => _localizer.WithCulture(culture); public virtual LocalizedString this[[NotNull] string name] => _localizer[name]; public virtual LocalizedString this[[NotNull] string name, params object[] arguments] =>
_localizer[name, arguments]; public virtual LocalizedString GetString([NotNull] string name) => _localizer.GetString(name); public virtual LocalizedString GetString([NotNull] string name, params object[] arguments) =>
_localizer.GetString(name, arguments); public IEnumerator<LocalizedString> GetEnumerator() => _localizer.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _localizer.GetEnumerator();
}

StringLocalizer

根据上面的介绍,我们可以推断该类库的使用方式如下:

public void Test()
{
IStringLocalizerFactory factory=new ResourceManagerStringLocalizerFactory();
IStringLocalizer localizer=new StringLocalizer<TType>(factory);
//IStringLocalizer<TType> localizer=new StringLocalizer<TType>();
//localizer=localizer.WithCulture(CultureInfo.CurrentUICulture);
var localizedString=localizer.GetString(key);
}

[StringLocalizer<TResource>的作用就是隐藏具体IStringLocalizer,使我们不用关心是哪个IStringLocalizer,这样做对于直接书写代码可能看不出直接意义,但是如果使用依赖注入,则可以明显的看出好处,我们可以为IStringLocalizer<TType>直接注入StringLocalizer<TType>类]

[如果对于依赖注入了解不多,可以看下篇博客:DependencyInjection项目代码分析-目录,略长]

Microsoft.Framework.Localization

  • ResourceManagerStringLocalizerFactory:创建ResourceManagerStringLocalizer类资源
  • ResourceManagerStringLocalizer:resx多语言文件的访问器(实际该代码并未另起灶炉,而是使用了ResourceManager类)
  • ResourceManagerWithCultureStringLocalizer:ResourceManagerStringLocalizer的子类,提供多语言访问接口。该类实际上是在父类中WithCulture中创建,而该方法内实际也是一个类似于代理模式的设计
  • LocalizationServiceCollectionExtensions类:该类将ResourceManagerStringLocalizerFactory注入到IStringLocalizerFactory接口,StringLocalizer<T> 注入到IStringLocalizer<T> 接口。
public class ResourceManagerStringLocalizerFactory : IStringLocalizerFactory
{
private readonly IApplicationEnvironment _applicationEnvironment; public ResourceManagerStringLocalizerFactory([NotNull] IApplicationEnvironment applicationEnvironment)
{
_applicationEnvironment = applicationEnvironment;
} public IStringLocalizer Create([NotNull] Type resourceSource)
{
var typeInfo = resourceSource.GetTypeInfo();
var assembly = new AssemblyWrapper(typeInfo.Assembly);
var baseName = typeInfo.FullName;
return new ResourceManagerStringLocalizer(new ResourceManager(resourceSource), assembly, baseName);
} public IStringLocalizer Create([NotNull] string baseName, [NotNull] string location)
{
var assembly = Assembly.Load(new AssemblyName(location ?? _applicationEnvironment.ApplicationName)); return new ResourceManagerStringLocalizer(
new ResourceManager(baseName, assembly),
new AssemblyWrapper(assembly),
baseName);
}
}

ResourceManagerStringLocalizerFactory

public class ResourceManagerStringLocalizer : IStringLocalizer
{
private static readonly ConcurrentDictionary<string, IList<string>> _resourceNamesCache =
new ConcurrentDictionary<string, IList<string>>(); private readonly ConcurrentDictionary<string, object> _missingManifestCache =
new ConcurrentDictionary<string, object>(); private readonly ResourceManager _resourceManager;
private readonly AssemblyWrapper _resourceAssemblyWrapper;
private readonly string _resourceBaseName; public ResourceManagerStringLocalizer(
[NotNull] ResourceManager resourceManager,
[NotNull] Assembly resourceAssembly,
[NotNull] string baseName)
: this(resourceManager, new AssemblyWrapper(resourceAssembly), baseName)
{ } public ResourceManagerStringLocalizer(
[NotNull] ResourceManager resourceManager,
[NotNull] AssemblyWrapper resourceAssemblyWrapper,
[NotNull] string baseName)
{
_resourceAssemblyWrapper = resourceAssemblyWrapper;
_resourceManager = resourceManager;
_resourceBaseName = baseName;
} public virtual LocalizedString this[[NotNull] string name]
{
get
{
var value = GetStringSafely(name, null);
return new LocalizedString(name, value ?? name, resourceNotFound: value == null);
}
} public virtual LocalizedString this[[NotNull] string name, params object[] arguments]
{
get
{
var format = GetStringSafely(name, null);
var value = string.Format(format ?? name, arguments);
return new LocalizedString(name, value, resourceNotFound: format == null);
}
} public IStringLocalizer WithCulture(CultureInfo culture)
{
return culture == null
? new ResourceManagerStringLocalizer(_resourceManager, _resourceAssemblyWrapper, _resourceBaseName)
: new ResourceManagerWithCultureStringLocalizer(_resourceManager,
_resourceAssemblyWrapper,
_resourceBaseName,
culture);
} protected string GetStringSafely([NotNull] string name, CultureInfo culture)
{
var cacheKey = $"name={name}&culture={(culture ?? CultureInfo.CurrentUICulture).Name}"; if (_missingManifestCache.ContainsKey(cacheKey))
{
return null;
} try
{
return culture == null ? _resourceManager.GetString(name) : _resourceManager.GetString(name, culture);
}
catch (MissingManifestResourceException)
{
_missingManifestCache.TryAdd(cacheKey, null);
return null;
}
} public virtual IEnumerator<LocalizedString> GetEnumerator() => GetEnumerator(CultureInfo.CurrentUICulture); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); protected IEnumerator<LocalizedString> GetEnumerator([NotNull] CultureInfo culture)
{
var resourceNames = GetResourceNamesFromCultureHierarchy(culture); foreach (var name in resourceNames)
{
var value = GetStringSafely(name, culture);
yield return new LocalizedString(name, value ?? name, resourceNotFound: value == null);
}
} internal static void ClearResourceNamesCache() => _resourceNamesCache.Clear(); private IEnumerable<string> GetResourceNamesFromCultureHierarchy(CultureInfo startingCulture)
{
var currentCulture = startingCulture;
var resourceNames = new HashSet<string>(); while (true)
{
try
{
var cultureResourceNames = GetResourceNamesForCulture(currentCulture);
foreach (var resourceName in cultureResourceNames)
{
resourceNames.Add(resourceName);
}
}
catch (MissingManifestResourceException) { } if (currentCulture == currentCulture.Parent)
{
// currentCulture begat currentCulture, probably time to leave
break;
} currentCulture = currentCulture.Parent;
} return resourceNames;
} private IList<string> GetResourceNamesForCulture(CultureInfo culture)
{
var resourceStreamName = _resourceBaseName;
if (!string.IsNullOrEmpty(culture.Name))
{
resourceStreamName += "." + culture.Name;
}
resourceStreamName += ".resources"; var cacheKey = $"assembly={_resourceAssemblyWrapper.FullName};resourceStreamName={resourceStreamName}"; var cultureResourceNames = _resourceNamesCache.GetOrAdd(cacheKey, key =>
{
var names = new List<string>();
using (var cultureResourceStream = _resourceAssemblyWrapper.GetManifestResourceStream(key))
using (var resources = new ResourceReader(cultureResourceStream))
{
foreach (DictionaryEntry entry in resources)
{
var resourceName = (string)entry.Key;
names.Add(resourceName);
}
} return names;
}); return cultureResourceNames;
}
}

ResourceManagerStringLocalizer

public class ResourceManagerWithCultureStringLocalizer : ResourceManagerStringLocalizer
{
private readonly CultureInfo _culture; public ResourceManagerWithCultureStringLocalizer(
[NotNull] ResourceManager resourceManager,
[NotNull] Assembly assembly,
[NotNull] string baseName,
[NotNull] CultureInfo culture)
: base(resourceManager, assembly, baseName)
{
_culture = culture;
} public ResourceManagerWithCultureStringLocalizer(
[NotNull] ResourceManager resourceManager,
[NotNull] AssemblyWrapper assemblyWrapper,
[NotNull] string baseName,
[NotNull] CultureInfo culture)
: base(resourceManager, assemblyWrapper, baseName)
{
_culture = culture;
} public override LocalizedString this[[NotNull] string name]
{
get
{
var value = GetStringSafely(name, _culture);
return new LocalizedString(name, value ?? name);
}
} public override LocalizedString this[[NotNull] string name, params object[] arguments]
{
get
{
var format = GetStringSafely(name, _culture);
var value = string.Format(_culture, format ?? name, arguments);
return new LocalizedString(name, value ?? name, resourceNotFound: format == null);
}
} public override IEnumerator<LocalizedString> GetEnumerator() => GetEnumerator(_culture);
}

ResourceManagerWithCultureStringLocalizer

public static class LocalizationServiceCollectionExtensions
{
public static IServiceCollection AddLocalization([NotNull] this IServiceCollection services)
{
services.TryAdd(new ServiceDescriptor(
typeof(IStringLocalizerFactory),
typeof(ResourceManagerStringLocalizerFactory),
ServiceLifetime.Singleton));
services.TryAdd(new ServiceDescriptor(
typeof(IStringLocalizer<>),
typeof(StringLocalizer<>),
ServiceLifetime.Transient)); return services;
}
}

LocalizationServiceCollectionExtensions

由于依赖注入的关系所以我们可以将代码简单的修改成如下:

          //var services = new ServiceCollection();
//services.AddLocalization(); 系统初始化时执行过该部分代码
public string Test(string key)
{
var localizer=Provider.GetService<IStringLocalizer<RescoureType>>();
//localizer=localizer.WithCulture(CultureInfo.CurrentUICulture);
var localizedString=localizer.GetString(key);
if(localizedString.ResourceNotFound){
reuturn null;
}
return localizedString.Value;
}

[Asp.net 5] Localization-resx资源文件的管理的更多相关文章

  1. 解决asp&period;net mvc中&ast;&period;resx资源文件访问报错

    个人笔记 问题重现 在asp.net mvc中,使用资源文件会出现一个问题,例如: 紧接着我进入视图界面,输入下面代码: <a href="javascript:void(0);&qu ...

  2. &period;net RESX资源文件

    RESX资源文件最大的优势就是: 支持多语言 快速创建资源 管理方便 RESX可以支持多语言,Visual Studio编译后会出现附属程序集(satellite assembly),事实上是连接器( ...

  3. VS下对Resx资源文件的操作

    原文:VS下对Resx资源文件的操作 读取 using System.IO; using System.Resources; using System.Collections; using Syste ...

  4. asp&period;net core合并压缩资源文件引发的学习之旅

    0. 在asp.net core中使用BuildBundlerMinifier合并压缩资源文件 在asp.net mvc中可以使用Bundle来压缩合并css,js 不知道的见:http://www. ...

  5. asp&period;net core合并压缩资源文件(转载)

    在asp.net core中使用BuildBundlerMinifier合并压缩资源文件 在asp.net mvc中可以使用Bundle来压缩合并css,js 不知道的见:http://www.cnb ...

  6. C&num;调用Resources&period;resx资源文件中的资源

    使用到了.NET中的资源文件,也就是Resources.resx,于是就学会了如何调用资源文件中的资源.首先,资源文件可以从项目属性中的资源标签添加.比如,我添加一个图片,叫做aaa.png,添加入资 ...

  7. PyQt&lpar;Python&plus;Qt&rpar;学习随笔:Qt Designer中图像资源的使用及资源文件的管理

    一.概述 在Qt Designer中要使用图片资源有三种方法:通过图像文件指定.通过资源文件指定.通过theme主题方式指定,对应的设置界面在需要指定图像的属性栏如windowIcon中通过点击属性设 ...

  8. Asp&period;net 引用css&sol;js资源文件

    注意Page.ResolveUrl之前的双引号,不是单引号 <script type="text/javascript" src="<%= Page.Reso ...

  9. Asp&period;net中使用资源文件实现网站多语言

    首先需要新建一个ASP.NET Web Application.然后右键项目文件Add->Add ASP.NET Folder->App-GlobalResources. 新建好资源文件夹 ...

随机推荐

  1. 在Windows和Linux上安装paramiko模块以及easy&lowbar;install的安装方法

    一.paramiko模块有什么用? paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接.由于使用的是python这样的能够跨平台运行的语言 ...

  2. 父类方法中的this

    一直在用一些东西,却总是感觉有一些疑惑,今天发现了自己一个及其致命的意识错误.关于父类中this关键字到底是谁的问题.请看代码 父类Parent public class Parent { publi ...

  3. phpcms v9 搬家

    1.修改/caches/configs/system.php里面所有和域名有关的,把以前的老域名修改为新域名. 2.进入后台设置--站点管理,对相应的站点的域名修改为新域名. 3.点击后台右上角的更新 ...

  4. c&num; 轻量级 ORM 框架 之 Model解析 &lpar;四&rpar;

    关于orm框架设计,还有必要说的或许就是Model解析了,也是重要的一个环节,在实现上还是相对比较简单的. Model解析,主要用到的技术是反射了,即:把类的属性与表的字段做映射. 把自己的设计及实现 ...

  5. Jackson - Quickstart

    JSON Three Ways Jackson offers three alternative methods (one with two variants) for processing JSON ...

  6. 深入C语言可变参数&lpar;va&lowbar;arg&comma;va&lowbar;list&comma;va&lowbar;start&comma;va&lowbar;end&comma;&lowbar;INTSIZEOF&rpar;

    一.什么是可变参数 在C语言编程中有时会遇到一些参数个数可变的函数,例如printf(),scanf()函数,其函数原型为: int printf(const char* format,…),int ...

  7. oracle日期计算

    查询某月有多少天.代码例如以下: select to_number(add_months( trunc(to_date('2014-11-4 11:13:53','yyyy-mm-dd hh24:mi ...

  8. &lpar;Release Candidate&rpar;Candidate

    RC:(Release Candidate)Candidate是候选人的意思,用在软件或者操作系统上就是候选版本

  9. 作业07-Java GUI编程

    1. 本周学习总结 1.1 思维导图:Java图形界面总结 1.2 可选:使用常规方法总结其他上课内容. 关于事件.事件源.事件监听器的总结: 事件:用户在GUI上进行的操作,如鼠标单击.输入文字.关 ...

  10. 微信公众号开发前端获取openId

    参考 https://blog.csdn.net/qq_35430000/article/details/79299529