帐户控制器未正确注册
我有一个使用Identity的具有单个用户帐户的ASP.NET MVC应用程序。在我的帐户控制器中,我有一个UserMappingService要注入。
有两个AccountController构造函数,一个最初是空的构造函数是引起问题的一个。我需要在这里注入UserMappingService。在将Service添加到构造函数的参数之前,我能够通过将其添加到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)仅适用于默认的无参数构造函数,但在这种情况下我不知道如何注册控制器。
答案 0 :(得分:0)
您可以这样指定依赖项类型:
var ctr = new InjectionConstructor(typeof(IUserMappingService));
container.RegisterType<AccountController>(ctr);
或者您可以用InjectionConstructorAttribute
标记您的构造函数:
[InjectionConstructor]
public AccountController(IUserMappingService mappingService)
{
userMappingService = mappingService;
}