MVC Identity 2和Unity 4 - DI RoleStore

时间:2015-11-16 14:45:51

标签: c# asp.net-mvc entity-framework dependency-injection ioc-container

我正在尝试将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会出错:

  

类型&#39; Microsoft.AspNet.Identity.EntityFramework.RoleStore&#39;不能用作类型参数&#39; TTo&#39;在泛型类型或方法中,UnityContainerExtensions.RegisterType(IUnityContainer,params InjectionMember [])&#39;。   
  来自&#39; Microsoft.AspNet.Identity.EntityFramework.RoleStore&#39;没有隐式引用转换。到&#39; Microsoft.AspNet.Identity.IRoleStore&#39;。

1 个答案:

答案 0 :(得分:1)

我找到了它。在UnityControllerFactory类中,您执行以下操作:

_container.RegisterType<IRoleStore<IdentityRole, string>,
    RoleStore<IdentityRole, string, IdentityUserRole>>(injectionConstructor);

并在UserController类中:

public UserController(IUserStore<IdentityUser> userStore,
    IRoleStore<IdentityRole, string> roleStore)
{ ... }