asp.net-mvc - 如何将 IStringLocalizer 注入(inject) IApplicationModelConvention?

标签 asp.net-mvc asp.net-core .net-core

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

关于asp.net-mvc - 如何将 IStringLocalizer 注入(inject) IApplicationModelConvention?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53869945/

相关文章:

c# - ASP.NET Core MVC Google Auth 注销问题

c# - 正常关闭和当前正在处理的请求

c# - 尝试在 ActionResult 中返回 HTML 会导致 HTTP 406 错误

c# - ASP.NET MVC View 内部 View

c# - TFS 和库在 nuget 中不可用

asp.net - .NET Core IoC RegisterAssemblyTypes等效项

c# - 仅针对特定用户的 Asp.net Core Windows 身份验证

mysql - 如何在已发布文件夹之外执行可访问 mysql 的程序?

.net-core - .HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase 在 .net core 2.1 中不起作用?

c# - 为什么尾随 %20(在本例中为有效数据)会终止 asp.net mvc 路由