为 ASP.NET Identity 配置 Unity DI [英] Configure Unity DI for ASP.NET Identity
问题描述
我成功地将 Unity 用于所有常规构造函数注入,例如存储库等,但我无法让它与 ASP.NET Identity 类一起使用.设置是这样的:
I'm using Unity successfully for all regular constructor injection such as repositories etc., but I can't get it working with the ASP.NET Identity classes. The setup is this:
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 配置:
with these configs for Unity:
unity.RegisterType<AccountController>();
unity.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
unity.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
这与 Autofac 的其他帖子相同,例如 Ninject,但在我的情况下不起作用.错误信息是:
That's the same as other posts here for Autofac, Ninject e.g., but it doesn't work in my case. The error message is:
尝试创建类型为AccountController"的控制器时出错.确保控制器具有无参数的公共构造函数.当然是手工创作作品:
An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor. Manual creation works of course:
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>("Mongo")))
{
}
怎么了?
更新
正如@emodendroket 所建议的那样,将代码缩短为这样可以解决问题.不需要 Unity.Mvc 包.
As suggested by @emodendroket, shortening the code to this does the trick. No need for the Unity.Mvc package.
unity.RegisterType<IUserStore<IdentityUser>,
MyCustomUserStore>(new HierarchicalLifetimeManager());
和
public AccountController(UserManager<IdentityUser> _userManager,
IAccountRepository _account)
{
// ...
推荐答案
您还需要解决UserManager.以下是如何使用 UserManager 和 RoleManager 执行此操作的示例.在这个示例中,我使用了常规的 Unity 3 包,而不是派生类或引导程序之一(过去它们有一些问题).
You also need to resolve the UserManager. The following is an example how you could do it with the UserManager and the RoleManager. In this sample I use the regular Unity 3 package instead of one of the derivates or bootstrappers (had some problems with them in the past).
账户控制器
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public AccountController(IUserStore<ApplicationUser> userStore, IRoleStore<IdentityRole> roleStore)
{
_userManager = new UserManager<ApplicationUser>(userStore);
_roleManager = new RoleManager<IdentityRole>(roleStore);
}
Unity Bootstrapper
var accountInjectionConstructor = new InjectionConstructor(new IdentitySampleDbModelContext(configurationStore));
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(accountInjectionConstructor);
container.RegisterType<IRoleStore<IdentityRole>, RoleStore<IdentityRole>>(accountInjectionConstructor);
这篇关于为 ASP.NET Identity 配置 Unity DI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!