The type RoleStore is not assignable

2020-07-13 16:49发布

问题:

I'm trying to set up dependency injection with Autofac for project using MVC5 and EF6.

I'm having a hard time figuring out how to decouple correctly the EntityFramework.RoleStore<EntityFramework.IdentityRole> implementation.
I would like have dependency only on Identity.IRoleStore<Identity.IRole> but I'm aware that for generic classes I need to specify the concrete implementation, not the interface.

This is what I tried:

        builder.RegisterType<IdentityRole>().As<IRole>();
        builder.RegisterType<RoleManager<IRole>>();
        builder.RegisterType<RoleStore<IdentityRole>>().As<IRoleStore<IRole>>();
        builder.Register(c => new RoleManager<IRole>(c.Resolve<IRoleStore<IRole>>()));

The full error message:

The type 'Microsoft.AspNet.Identity.EntityFramework.RoleStore1[Microsoft.AspNet.Identity.EntityFramework.IdentityRole]' is not assignable to service 'Microsoft.AspNet.Identity.IRoleStore1[[Microsoft.AspNet.Identity.IRole, Microsoft.AspNet.Identity.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]'.

回答1:

Bit late to the party but this worked for me with Autofac:

builder.RegisterType<RoleStore<IdentityRole>>().As<IRoleStore<IdentityRole, string>>();

My full module for reference:

builder.RegisterType<UserStore<ApplicationUser>>().As<IUserStore<ApplicationUser>>();
builder.RegisterType<RoleStore<IdentityRole>>().As<IRoleStore<IdentityRole, string>>();
builder.RegisterType<ApplicationUserManager>();
builder.RegisterType<ApplicationRoleManager>();  

I'm using wrappers for the UserManager and RoleManager

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }
}

public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
        : base(roleStore)
    {            
    }       
}