JonasVH
JonasVH

Reputation: 83

MVC Identity 2 and Unity 4 - DI the RoleStore

I am trying to setup MVC Unity in combination with MVC Identity. The controller who takes care of registering and logging in users should have a user and role manager. So i create the following 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);
    }
}

I also have a class called UnityControllerFactory which describes the necessary bindings for 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);
    }
}

Registering the RoleStore in Unity gives an error:

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'.

Upvotes: 3

Views: 511

Answers (1)

JonasVH
JonasVH

Reputation: 83

I've found it. In the UnityControllerFactory class you do the following:

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

and in the UserController class:

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

Upvotes: 2

Related Questions