我成功地使用 Unity 进行所有常规构造函数注入(例如存储库等),但无法使其与 ASP.NET Identity 类一起使用。设置是这样的:
public class AccountController : ApiController
{
private UserManager<ApplicationUser> _userManager { get; set; }
public AccountController(UserManager<ApplicationUser> userManager)
{
if (userManager == null) { throw new ArgumentNullException("userManager"); }
_userManager = userManager;
}
// ...
}
Unity 的这些配置:
unity.RegisterType<AccountController>();
unity.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
unity.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
这与 Autofac、Ninject 等其他帖子相同,但在我的情况下不起作用。错误信息是:
尝试创建“AccountController”类型的控制器时发生错误。确保控制器具有无参数公共构造函数。
手动创建当然有效:
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>("Mongo")))
{
}
怎么了?
UPDATE
正如 @emodendroket 所建议的,将代码缩短为这样就可以了。不需要Unity.Mvc包。
unity.RegisterType<IUserStore<IdentityUser>,
MyCustomUserStore>(new HierarchicalLifetimeManager());
and
public AccountController(UserManager<IdentityUser> _userManager,
IAccountRepository _account)
{
// ...