[英]Registering AccountController with Unity IoC
Account Controller does not Register correctly 帐户控制器未正确注册
I have an ASP.NET MVC application with Individual user accounts using Identity. 我有一个使用Identity的个人用户帐户的ASP.NET MVC应用程序。 In my account controller I have a UserMappingService that I would like to inject.
在我的帐户控制器中,我有一个UserMappingService要注入。
There are two AccountController constructors, the one that was originally an empty constructor is the one that is causing issues. 有两个AccountController构造函数,一个原来是空的构造函数,一个是引起问题的构造函数。 I need to inject the UserMappingService here.
我需要在这里注入UserMappingService。 Before I added the Service to the parameters of the constructor I was able to make the controller register the empty constructor by adding this to the UnityConfig.cs
在将服务添加到构造函数的参数之前,我能够通过将控制器添加到UnityConfig.cs来使控制器注册空的构造函数
//parameterless constructor in AccountController.cs
public AccountController()
{
}
// From UnityConfig.cs in RegisterTypes method
container.RegisterType<AccountController>(new InjectionConstructor());
The problem is that once I add the service as a parameter, I get errors. 问题是,一旦将服务添加为参数,就会收到错误消息。
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());
}
Resulting error upon runtime is: Error in RegisterType(Invoke.Constructor()) ArgumentException: No member matching data has been found. 运行时导致的错误是:RegisterType(Invoke.Constructor())中的错误ArgumentException:找不到与成员匹配的数据。
I am pretty sure the (InjectionConstructor) is only good for for the default parameterless constructor, but I don't know how else to Register the controller in this case. 我很确定(InjectionConstructor)仅适用于默认的无参数构造函数,但是在这种情况下我不知道如何注册控制器。
You can spec the dependency type like this: 您可以这样指定依赖项类型:
var ctr = new InjectionConstructor(typeof(IUserMappingService));
container.RegisterType<AccountController>(ctr);
Or you can flag your constructor with InjectionConstructorAttribute
: 或者,您可以使用
InjectionConstructorAttribute
标记您的构造函数:
[InjectionConstructor]
public AccountController(IUserMappingService mappingService)
{
userMappingService = mappingService;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.