【问题标题】:MVC Identity 2 and Unity 4 - DI the RoleStoreMVC Identity 2 和 Unity 4 - DI RoleStore
【发布时间】:2015-11-16 14:45:50
【问题描述】:

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

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 会报错:

类型“Microsoft.AspNet.Identity.EntityFramework.RoleStore”不能用作泛型类型或方法“UnityContainerExtensions.RegisterType(IUnityContainer, params InjectionMember[])”中的类型参数“TTo”。
没有从“Microsoft.AspNet.Identity.EntityFramework.RoleStore”到“Microsoft.AspNet.Identity.IRoleStore”的隐式引用转换。

【问题讨论】:

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


    【解决方案1】:

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

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

    在 UserController 类中:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      • 2017-06-29
      • 1970-01-01
      相关资源
      最近更新 更多