首页 > 解决方案 > 向 Unity IoC 注册 AccountController

问题描述

帐户控制器未正确注册

我有一个 ASP.NET MVC 应用程序,其中包含使用身份的个人用户帐户。在我的帐户控制器中,我有一个要注入的 UserMappingService。

有两个 AccountController 构造函数,一个最初是空的构造函数是导致问题的那个。我需要在这里注入 UserMappingService。在将服务添加到构造函数的参数之前,我可以通过将其添加到 UnityConfig.cs 来使控制器注册空构造函数

//parameterless constructor in AccountController.cs
public AccountController()
    {

    } 

// From UnityConfig.cs in RegisterTypes method
container.RegisterType<AccountController>(new InjectionConstructor());

问题是,一旦我将服务添加为参数,就会出现错误。

private IUserMappingService userMappingService;

//constructor with interface in the parameter AccountController.cs
public AccountController(IUserMappingService mappingService)
    {
        userMappingService = mappingService;
    }

//From UnityConfig.cs
 public static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<IUserMappingService, UserMappingService>();
        container.RegisterType<AccountController>(new InjectionConstructor());
    }

运行时产生的错误是:RegisterType(Invoke.Constructor()) 中的错误 ArgumentException:未找到匹配的成员数据。

我很确定 (InjectionConstructor) 仅适用于默认的无参数构造函数,但我不知道在这种情况下如何注册控制器。

标签: c#asp.net-mvcunity-containerioc-container

解决方案


您可以像这样指定依赖类型:

var ctr = new InjectionConstructor(typeof(IUserMappingService));
container.RegisterType<AccountController>(ctr);

或者您可以使用以下标记您的构造函数InjectionConstructorAttribute

[InjectionConstructor]
public AccountController(IUserMappingService mappingService)
{
     userMappingService = mappingService;
}

推荐阅读