Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 567
JonasVH Avatar asked Nov 27 '25 21:11

JonasVH


1 Answers

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)
{ ... }
like image 146
JonasVH Avatar answered Nov 29 '25 09:11

JonasVH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!