coredx

前言

       最近的新型冠状病毒流行让很多人主动在家隔离,希望疫情能快点消退。武汉加油,中国必胜!

       Asp.Net Core 提供了内置的网站国际化(全球化与本地化)支持,微软还内置了基于 resx 资源字符串的国际化服务组件。可以在入门教程中找到相关内容。

       但是内置实现方式有一个明显缺陷,resx 资源是要静态编译到程序集中的,无法在网站运行中临时编辑,灵活性较差。幸好我找到了一个基于数据库资源存储的组件,这个组件完美解决了 resx 资源不灵活的缺陷,经过适当的设置,可以在第一次查找资源时顺便创建数据库记录,而我们要做的就是访问一次相应的网页,让组件创建好记录,然后我们去编辑相应的翻译字段并刷新缓存即可。

       但是!又是但是,经过一段时间的使用,发现基于数据库的方式依然存在缺陷,开发中难免有需要删除并重建数据库,初始化环境。这时,之前辛辛苦苦编辑的翻译就会一起灰飞烟灭 (╯‵□′)╯︵┻━┻ 。而 resx 资源却完美避开了这个问题,这时我就在想,能不能让他们同时工作,兼顾灵活性与稳定性,鱼与熊掌兼得。

       经过一番摸索,终于得以成功,在此开贴记录分享。

正文

设置并启用国际化服务组件

       安装 Nuget 包 Localization.SqlLocalizer,这个包依赖 EF Core 进行数据库操作。然后在 Startup 的 ConfigureServices 方法中加入以下代码注册  EF Core 上下文:

1 services.AddDbContext<LocalizationModelContext>(options =>
2     {
3         options.UseSqlServer(connectionString);
4     },
5     ServiceLifetime.Singleton,
6     ServiceLifetime.Singleton);

       注册自制的混合国际化服务:

services.AddMixedLocalization(opts => { opts.ResourcesPath = "Resources"; }, options => options.UseSettings(true, false, true, true));

       注册请求本地化配置:

 1 services.Configure<RequestLocalizationOptions>(
 2     options =>
 3     {
 4         var cultures =  Configuration.GetSection("Internationalization").GetSection("Cultures")
 5         .Get<List<string>>()
 6         .Select(x => new CultureInfo(x)).ToList();
 7         var supportedCultures = cultures;
 8 
 9         var defaultRequestCulture = cultures.FirstOrDefault() ?? new CultureInfo("zh-CN");
10         options.DefaultRequestCulture = new RequestCulture(culture: defaultRequestCulture, uiCulture: defaultRequestCulture);
11         options.SupportedCultures = supportedCultures;
12         options.SupportedUICultures = supportedCultures;
13     });

       注册 MVC 本地化服务:

1 services.AddMvc()
2     //注册视图本地化服务
3     .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix, opts => { opts.ResourcesPath = "Resources"; })
4     //注册数据注解本地化服务
5     .AddDataAnnotationsLocalization();

       在 appsettings.json 的根对象节点添加属性:

"Internationalization": {
  "Cultures": [
    "zh-CN",
    "en-US"
  ]
}

       在某个控制器加入以下动作:

 1 public IActionResult SetLanguage(string lang)
 2 {
 3     var returnUrl = HttpContext.RequestReferer() ?? "/Home";
 4 
 5     Response.Cookies.Append(
 6         CookieRequestCultureProvider.DefaultCookieName,
 7         CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(lang)),
 8         new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
 9     );
10 
11     return Redirect(returnUrl);
12 }

       准备一个页面调用这个动作切换语言。然后,大功告成!

       这个自制服务遵循以下规则:优先查找基于 resx 资源的翻译数据,如果找到则直接使用,如果没有找到,再去基于数据库的资源中查找,如果找到则正常使用,如果没有找到则按照对服务的配置决定是否在数据库中生成记录并使用。

自制混合国际化服务组件的实现

       本体:

  1 public interface IMiscibleStringLocalizerFactory : IStringLocalizerFactory
  2 {
  3 }
  4 
  5 public class MiscibleResourceManagerStringLocalizerFactory : ResourceManagerStringLocalizerFactory, IMiscibleStringLocalizerFactory
  6 {
  7     public MiscibleResourceManagerStringLocalizerFactory(IOptions<LocalizationOptions> localizationOptions, ILoggerFactory loggerFactory) : base(localizationOptions, loggerFactory)
  8     {
  9     }
 10 }
 11 
 12 public class MiscibleSqlStringLocalizerFactory : SqlStringLocalizerFactory, IStringExtendedLocalizerFactory, IMiscibleStringLocalizerFactory
 13 {
 14     public MiscibleSqlStringLocalizerFactory(LocalizationModelContext context, DevelopmentSetup developmentSetup, IOptions<SqlLocalizationOptions> localizationOptions) : base(context, developmentSetup, localizationOptions)
 15     {
 16     }
 17 }
 18 
 19 public class MixedStringLocalizerFactory : IStringLocalizerFactory
 20 {
 21     private readonly IEnumerable<IMiscibleStringLocalizerFactory> _localizerFactories;
 22     private readonly ILogger<MixedStringLocalizerFactory> _logger;
 23 
 24     public MixedStringLocalizerFactory(IEnumerable<IMiscibleStringLocalizerFactory> localizerFactories, ILogger<MixedStringLocalizerFactory> logger)
 25     {
 26         _localizerFactories = localizerFactories;
 27         _logger = logger;
 28     }
 29 
 30     public IStringLocalizer Create(string baseName, string location)
 31     {
 32         return new MixedStringLocalizer(_localizerFactories.Select(x =>
 33         {
 34             try
 35             {
 36                 return x.Create(baseName, location);
 37             }
 38             catch (Exception ex)
 39             {
 40                 _logger.LogError(ex, ex.Message);
 41                 return null;
 42             }
 43         }));
 44     }
 45 
 46     public IStringLocalizer Create(Type resourceSource)
 47     {
 48         return new MixedStringLocalizer(_localizerFactories.Select(x =>
 49         {
 50             try
 51             {
 52                 return x.Create(resourceSource);
 53             }
 54             catch (Exception ex)
 55             {
 56                 _logger.LogError(ex, ex.Message);
 57                 return null;
 58             }
 59         }));
 60     }
 61 }
 62 
 63 public class MixedStringLocalizer : IStringLocalizer
 64 {
 65     private readonly IEnumerable<IStringLocalizer> _stringLocalizers;
 66 
 67     public MixedStringLocalizer(IEnumerable<IStringLocalizer> stringLocalizers)
 68     {
 69         _stringLocalizers = stringLocalizers;
 70     }
 71 
 72     public virtual LocalizedString this[string name]
 73     {
 74         get
 75         {
 76             var localizer = _stringLocalizers.SingleOrDefault(x => x is ResourceManagerStringLocalizer);
 77             var result = localizer?[name];
 78             if (!(result?.ResourceNotFound ?? true)) return result;
 79 
 80             localizer = _stringLocalizers.SingleOrDefault(x => x is SqlStringLocalizer) ?? throw new InvalidOperationException($"没有找到可用的 {nameof(IStringLocalizer)}");
 81             result = localizer[name];
 82             return result;
 83         }
 84     }
 85 
 86     public virtual LocalizedString this[string name, params object[] arguments]
 87     {
 88         get
 89         {
 90             var localizer = _stringLocalizers.SingleOrDefault(x => x is ResourceManagerStringLocalizer);
 91             var result = localizer?[name, arguments];
 92             if (!(result?.ResourceNotFound ?? true)) return result;
 93 
 94             localizer = _stringLocalizers.SingleOrDefault(x => x is SqlStringLocalizer) ?? throw new InvalidOperationException($"没有找到可用的 {nameof(IStringLocalizer)}");
 95             result = localizer[name, arguments];
 96             return result;
 97         }
 98     }
 99 
100     public virtual IEnumerable<LocalizedString> GetAllStrings(bool includeParentCultures)
101     {
102         var localizer = _stringLocalizers.SingleOrDefault(x => x is ResourceManagerStringLocalizer);
103         var result = localizer?.GetAllStrings(includeParentCultures);
104         if (!(result?.Any(x => x.ResourceNotFound) ?? true)) return result;
105 
106         localizer = _stringLocalizers.SingleOrDefault(x => x is SqlStringLocalizer) ?? throw new InvalidOperationException($"没有找到可用的 {nameof(IStringLocalizer)}");
107         result = localizer?.GetAllStrings(includeParentCultures);
108         return result;
109     }
110 
111     [Obsolete]
112     public virtual IStringLocalizer WithCulture(CultureInfo culture)
113     {
114         throw new NotImplementedException();
115     }
116 }
117 
118 public class MixedStringLocalizer<T> : MixedStringLocalizer, IStringLocalizer<T>
119 {
120     public MixedStringLocalizer(IEnumerable<IStringLocalizer> stringLocalizers) : base(stringLocalizers)
121     {
122     }
123 
124     public override LocalizedString this[string name] => base[name];
125 
126     public override LocalizedString this[string name, params object[] arguments] => base[name, arguments];
127 
128     public override IEnumerable<LocalizedString> GetAllStrings(bool includeParentCultures)
129     {
130         return base.GetAllStrings(includeParentCultures);
131     }
132 
133     [Obsolete]
134     public override IStringLocalizer WithCulture(CultureInfo culture)
135     {
136         throw new NotImplementedException();
137     }
138 }
View Code

       注册辅助扩展:

 1 public static class MixedLocalizationServiceCollectionExtensions
 2 {
 3     public static IServiceCollection AddMixedLocalization(
 4         this IServiceCollection services,
 5         Action<LocalizationOptions> setupBuiltInAction = null,
 6         Action<SqlLocalizationOptions> setupSqlAction = null)
 7     {
 8         if (services == null) throw new ArgumentNullException(nameof(services));
 9 
10         services.AddSingleton<IMiscibleStringLocalizerFactory, MiscibleResourceManagerStringLocalizerFactory>();
11 
12         services.AddSingleton<IMiscibleStringLocalizerFactory, MiscibleSqlStringLocalizerFactory>();
13         services.TryAddSingleton<IStringExtendedLocalizerFactory, MiscibleSqlStringLocalizerFactory>();
14         services.TryAddSingleton<DevelopmentSetup>();
15 
16         services.TryAddTransient(typeof(IStringLocalizer<>), typeof(StringLocalizer<>));
17 
18         services.AddSingleton<IStringLocalizerFactory, MixedStringLocalizerFactory>();
19 
20         if (setupBuiltInAction != null) services.Configure(setupBuiltInAction);
21         if (setupSqlAction != null) services.Configure(setupSqlAction);
22 
23         return services;
24     }
25 }
View Code

 

      原理简介

       服务组件利用了 DI 中可以为同一个服务类型注册多个实现类型,并在构造方法中注入服务集合,便可以将注册的所有实现注入组件同时使用。要注意主控服务和工作服务不能注册为同一个服务类型,不然会导致循环依赖。 内置的国际化框架已经指明了依赖 IStringLocalizerFatory ,必须将主控服务注册为 IStringLocalizerFatory,工作服只能注册为其他类型,不过依然要实现 IStringLocalizerFatory,所以最方便的办法就是定义一个新服务类型作为工作服务类型并继承 IStringLocalizerFatory。

       想直接体验效果的可以到文章底部访问我的 Github 下载项目并运行。

结语

       这个组件是在计划集成 IdentityServer4 管理面板时发现那个组件使用了 resx 的翻译,而我的现存项目已经使用了数据库翻译存储,两者又不相互兼容的情况下产生的想法。

       当时 Localization.SqlLocalizer 旧版本(2.0.4)还存在无法在视图本地化时正常创建数据库记录的问题,也是我调试修复了 bug 并向原作者提交了拉取请求,原作者也在合并了我的修复后发布了新版本。

       这次在集成 IdentityServer4 管理面板时又发现了 bug,正准备联系原作者看怎么处理。

 

       转载请完整保留以下内容并在显眼位置标注,未经授权删除以下内容进行转载盗用的,保留追究法律责任的权利!

  本文地址:https://www.cnblogs.com/coredx/p/12271537.html

  完整源代码:Github

  里面有各种小东西,这只是其中之一,不嫌弃的话可以Star一下。

分类:

技术点:

相关文章: