Registering AccountController with Unity IoC



账户管理员未正确注册

我有一个ASP.NET MVC应用程序,其中包含使用Identity的个人用户帐户。在我的帐户控制器中,我有一个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.Construtor())中出错ArgumentException:未找到与数据匹配的成员。

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

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

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

或者你可以用InjectionConstructorAttribute:标记你的构造函数

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

最新更新