我使用Unity成功为所有常规构造注射,如仓库等,但我不能让它与ASP.NET身份类的工作.设置是这样的:
public class AccountController : ApiController
{
private UserManager<ApplicationUser> _userManager { get; set; }
public AccountController(UserManager<ApplicationUser> userManager)
{
if (userManager == null) { throw new ArgumentNullException("userManager"); }
_userManager = userManager;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
使用Unity的这些配置:
unity.RegisterType<AccountController>();
unity.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
unity.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
Run Code Online (Sandbox Code Playgroud)
这与Autofac,Ninject的其他帖子相同,例如,但在我的情况下它不起作用.错误消息是:
尝试创建"AccountController"类型的控制器时发生错误.确保控制器具有无参数的公共构造函数.手动创作当然是:
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>("Mongo")))
{
}
Run Code Online (Sandbox Code Playgroud)
怎么了?
UPDATE
正如@emodendroket所建议的,缩短代码就可以了.不需要Unity.Mvc包.
unity.RegisterType<IUserStore<IdentityUser>,
MyCustomUserStore>(new HierarchicalLifetimeManager());
Run Code Online (Sandbox Code Playgroud)
和
public AccountController(UserManager<IdentityUser> _userManager,
IAccountRepository _account)
{
// ...
Run Code Online (Sandbox Code Playgroud) c# asp.net dependency-injection unity-container asp.net-identity