Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject an IStringLocalizer into IApplicationModelConvention?

I have a custom convention that requires localized strings inside of it. AFAIK the only way to instantiate an IStringLocalizer is DependencyInjection.

How can I use an IStringLocalizer inside of my CustomConvention?

The convention isregistered like this

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());
      })
}
like image 298
Anarion Avatar asked Oct 12 '25 13:10

Anarion


1 Answers

The solution I had is not pretty.

You can do something like that, build the service provider to get an instance of the 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));
     })
}
like image 127
hockeylagu Avatar answered Oct 14 '25 09:10

hockeylagu