使用Unity IoC注册AccountController

4

账户控制器无法正确注册

我有一个使用Identity的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: 找不到匹配 data 的成员。

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

1个回答

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

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

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

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

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

1
谢谢!我最终使用了选项1——在注册类型时将InjectionConstructor作为参数传递。谢谢!! - Lee Ames

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