为什么执行时IStringLocalizer依赖项注入会引发错误

时间:2019-03-08 21:34:52

标签: c# .net asp.net-mvc

我真的是.net核心编程的新手,遇到了这个问题,我无法解决。该解决方案构建良好,并且显示了主页,但是当我执行任何操作(例如尝试登录)时,都会收到此错误:(AcademiejaarInst是域类)

InvalidOperationException: No suitable constructor found for entity type 'AcademiejaarInst'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'localizer' in 'AcademiejaarInst(IStringLocalizer<SharedResource> localizer)'. 

AcademiejaarInst的负责人

public class AcademiejaarInst
{

    private static IStringLocalizer<SharedResource> _localizer;
    public AcademiejaarInst(IStringLocalizer<SharedResource> localizer)
    {
        _localizer = localizer;
    }
...

如果我尝试进行迁移,情况也是如此。显然,本地化注入不正确,但是我不知道为什么。这些是StartUp.cs中的相关LoC。

    public void ConfigureServices(IServiceCollection services)
    {
      ...
      services.AddMvc(config => ... )
     .AddViewLocalization(o => o.ResourcesPath = "Resources")
     .AddDataAnnotationsLocalization(options => {
                    options.DataAnnotationLocalizerProvider = (type, factory) =>
                        factory.Create(typeof(SharedResource));
                });

     // I tried this but was absolutely not sure this would work.
     services.AddTransient<AcademiejaarInst>();
     services.AddSingleton<IStringLocalizer, StringLocalizer<SharedResource>>();
     services.AddLocalization(o => o.ResourcesPath = "Resources");

     services.Configure<RequestLocalizationOptions>(options =>
     {
         var supportedCultures = new[]
         {
                    new CultureInfo("nl-BE")
         };
         options.DefaultRequestCulture = new RequestCulture("nl-BE", "nl_BE");

         options.SupportedCultures = supportedCultures;

                options.SupportedUICultures = supportedCultures;
     });
     ...
   }

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

在AcademiejaarInst构造函数中,您期望的是IStringLocalizer<SharedResource>,但是此类型没有配置。

如果您更改

services.AddSingleton<IStringLocalizer, StringLocalizer<SharedResource>>();

services.AddSingleton(typeof(IStringLocalizer<SharedResource>), typeof(StringLocalizer<SharedResource));

它应该工作

答案 1 :(得分:0)

services.AddLocalization() 调用已经为接口 IStringLocalizer<T> 连接了适当的实现,因此您实际上不需要自己注入它,我认为这是您的问题的来源。

删除为 IStringLocalizer 接口注入特定实现的行应该可以解决您的问题。