如何将IStringLocalizer注入IApplicationModelConvention?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将IStringLocalizer注入IApplicationModelConvention?相关的知识,希望对你有一定的参考价值。
我有一个自定义约定,需要在其中的本地化字符串。 AFAIK实例化IStringLocalizer的唯一方法是DependencyInjection。
如何在CustomConvention中使用IStringLocalizer?
该惯例是这样注册的
public void ConfigureServices(IServiceCollection services)
{
//First I register the localization settings
services.AddLocalization(o =>
{
o.ResourcesPath = "Resources";
});
services.AddMvc(options =>
{
//My custom convention, I would need to inject an IStringLocalizer
//into constructor here, but I can' instantiate it
options.Conventions.Add(new LocalizationRouteConvention());
})
}
答案
我的解决方案并不漂亮。
您可以执行类似的操作,构建服务提供程序以获取StringLocalizer的实例。
public void ConfigureServices(IServiceCollection services)
{
//First I register the localization settings
services.AddLocalization(o =>
{
o.ResourcesPath = "Resources";
});
var stringLocalizer = services.BuildServiceProvider().GetService<IStringLocalizer<Resource>>();
services.AddMvc(options =>
{
//My custom convention, I would need to inject an IStringLocalizer
//into constructor here, but I can' instantiate it
options.Conventions.Add(new LocalizationRouteConvention(stringLocalizer));
})
}
以上是关于如何将IStringLocalizer注入IApplicationModelConvention?的主要内容,如果未能解决你的问题,请参考以下文章