尚未注册类型“Microsoft.AspNetCore.Mvc.Localization.IHtmlLocalizer”的服务

21

我尝试使用ASP.Core创建一个多语言网站。因此,在我的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>();
}

在我的_ViewImports.cs文件中,我有:

@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

错误:

An unhandled exception occurred while processing the request.

InvalidOperationException: No service for type 'Microsoft.AspNetCore.Mvc.Localization.IHtmlLocalizer' has been registered.
2个回答

31

添加一个类型到IHtmlLocalizer 就像文档所演示的那样。

@inject IHtmlLocalizer<MyType> MyTypeLocalizer

此外,我注意到您尚未注册ViewLocalization服务。您可能也需要这样做。
public void ConfigureServices(IServiceCollection services)
{
    services
       .AddLocalization(options => options.ResourcesPath = "Resources");

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

    ...

5
谢谢,services.AddMvc().AddViewLocalization() 很有帮助。 - Rroman
2
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Rroman

4

Asp.net core 5:

services
.AddControllersWithViews()
.AddViewLocalization();
            

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接