当我试图调用账户 Controller 时,我得到了这个错误,
[InvalidOperationException: The current type, Microsoft.AspNet.Identity.IUserStore`1[Proj1.Web.Models.ApplicationUser], is an interface and cannot be constructed. Are you missing a type mapping?]
但是在搜索之后我得到了它的工作;
container.RegisterType<AccountController>(new InjectionConstructor());
但为什么首先会出现此错误?
账户 Controller 有一个无参数的构造函数,
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
{
UserManager = userManager;
SignInManager = signInManager;
}
然后 ApplicationUserManager 具有以下无参数构造函数。
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
所以依赖是IUserStore。
现在,作为我的标准做法,我将执行以下操作:
container.RegisterType<IUserStore<ApplicationUser>,UserStore<ApplicationUser>>();
但我们却在做,这感觉就像魔法
container.RegisterType<AccountController>(new InjectionConstructor());
上面一行是什么意思?
最佳答案
InvalidOperationException
的原因是Unity在默认情况下会选择参数最多的构造函数作为构造函数来实例化对象。
在这种情况下会是
public AccountController(ApplicationUserManager userManager,
ApplicationSignInManager signInManager)
这取决于 ApplicationUserManager
这取决于 IUserStore<ApplicationUser>
的实现.似乎Unity中没有注册映射IUserStore
到具体类,以便 Unity 抛出异常。
原因
container.RegisterType<AccountController>(new InjectionConstructor());
有效的是这个注册有一个“空”InjectionConstructor
告诉 Unity 使用无参数构造函数:public AccountController()
在实例化 AccountController 时。这工作正常,因为没有额外的依赖关系需要解决。
这是否是您想要的将取决于您的实现,但通常您希望显式地将依赖项注入(inject)构造函数而不是使用无参数构造函数。
还要注意在这种情况下
container.RegisterType<IUserStore<ApplicationUser>,UserStore<ApplicationUser>>();
您还可以使用开放泛型进行注册,以便任何 IUserStore<T>
可以在不注册所有可能类型的 T 的情况下解决。
container.RegisterType(typeof(IUserStore<>), typeof(UserStore<>));
// Will resolve both concrete types
var userStore1 = container.Resolve<IUserStore<ApplicationUser>>();
var userStore2 = container.Resolve<IUserStore<OtherApplicationUser>>();
关于c# - IUserStore[Models.ApplicationUser] 不是通过 Unity Interface to Class 解析的,而是通过 InjectionConstructor 解析的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45429116/