No service for type "Microsoft.AspNetCore.Mvc.Localization.IHtmlLocalizer" is registered

I am trying with ASP.Core to have a multilingual website. So, I have in my StartUp.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization();
    services.Configure<RequestLocalizationOptions>(
    opts =>
    {
        var supportedCultures = new[]
        {
            new CultureInfo("de-DE"),
            new CultureInfo("de"),
            new CultureInfo("fr-FR"),
            new CultureInfo("fr"),
        };
        opts.DefaultRequestCulture = new RequestCulture("fr-FR");
        // Formatting numbers, dates, etc.
        opts.SupportedCultures = supportedCultures;
        // UI strings that we have localized.
        opts.SupportedUICultures = supportedCultures;
    });
    // Add framework services.
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
    services.AddMvc();
    // Add application services.
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();
}

In my _ViewImports.cs, I have:

@using System.Threading.Tasks
@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@using Microsoft.Extensions.Options

@inject IHtmlLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Errors:

An unhandled exception occurred while processing the request.

InvalidOperationException: No service for type 'Microsoft.AspNetCore.Mvc.Localization.IHtmlLocalizer' has been registered.
+4
source share
1 answer

Add the type to IHtmlLocalizer as shown in the docs .

@inject IHtmlLocalizer<MyType> MyTypeLocalizer

In addition, I noticed that you did not register the service ViewLocalization. You may also have to do this.

public void ConfigureServices(IServiceCollection services)
{
    services
       .AddLocalization(options => options.ResourcesPath = "Resources");

    services
      .AddMvc()
      .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix;

    ...
+5
source

Source: https://habr.com/ru/post/1659073/


All Articles