MVC Identity 2 and Unity 4 - DI the RoleStore
本文关键字:DI the RoleStore Unity Identity and MVC | 更新日期: 2023-09-27 18:22:09
我正在尝试将MVC Unity与MVC Identity结合起来进行设置。负责注册和登录用户的控制器应该有一个用户和角色管理器。所以我创建了以下类:
public class UserController : Controller
{
private readonly UserManager<IdentityUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public UserController(IUserStore<IdentityUser> userStore,
IRoleStore<IdentityRole> roleStore)
{
_userManager = new UserManager<IdentityUser>(userStore);
_roleManager = new RoleManager<IdentityRole>(roleStore);
}
}
我还有一个名为UnityControllerFactory的类,它描述了Unity:的必要绑定
public class UnityControllerFactory : DefaultControllerFactory
{
private IUnityContainer _container;
public UnityControllerFactory()
{
_container = new UnityContainer();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext,
Type controllerType)
{
if (controllerType != null)
{
return _container.Resolve(controllerType) as IController;
}
else
{
return base.GetControllerInstance(requestContext, controllerType);
}
}
private void AddBindings()
{
var injectionConstructor= new InjectionConstructor(new DbContext());
_container.RegisterType<IUserStore<IdentityUser>, UserStore<IdentityUser>>(
injectionConstructor);
_container.RegisterType<IRoleStore<IdentityRole>, RoleStore<IdentityRole>>(
injectionConstructor);
}
}
在Unity中注册RoleStore会出现错误:
类型"Microsoft.AspNet.Identity.EntityFramework.RoleStore"不能用作泛型类型或方法"UnityContainerExtensions.RegisterType(IUnityContainer,params InjectionMember[])"中的类型参数"TTo"。
没有从"Microsoft.AspNet.Identity.EntityFramework.RoleStore"到"Microsoft.AspNet.Identity.IRoleStore"的隐式引用转换。
我找到了它。在UnityControllerFactory类中,您可以执行以下操作:
_container.RegisterType<IRoleStore<IdentityRole, string>,
RoleStore<IdentityRole, string, IdentityUserRole>>(injectionConstructor);
在UserController类中:
public UserController(IUserStore<IdentityUser> userStore,
IRoleStore<IdentityRole, string> roleStore)
{ ... }