我有一个自定义约定,需要在其中的本地化字符串。 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));
})
}