MVC Identity 2 and Unity 4——DI the RoleStore

MVC Identity 2 and Unity 4 - DI the RoleStore

我正在尝试结合 MVC Identity 设置 MVC Unity。负责注册和登录用户的控制器应该有一个用户和角色管理器。所以我创建了以下 class:

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 的 class,它描述了 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报错:

The type 'Microsoft.AspNet.Identity.EntityFramework.RoleStore' cannot be used as type parameter 'TTo' in the generic type or method 'UnityContainerExtensions.RegisterType(IUnityContainer, params InjectionMember[])'.
There is no implicit reference conversion from 'Microsoft.AspNet.Identity.EntityFramework.RoleStore' to 'Microsoft.AspNet.Identity.IRoleStore'.

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

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

在用户控制器中 class:

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