【问题标题】:How do I inject Identity classes with Ninject?如何使用 Ninject 注入身份类?
【发布时间】:2015-03-17 01:30:24
【问题描述】:

我正在尝试在课程中使用 UserManager,但出现此错误:

Error activating IUserStore{ApplicationUser}
No matching bindings are available, and the type is not self-bindable.

我正在使用默认的 Startup.cs,它为每个请求设置一个实例:

app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

我能够获得 ApplicationDbContext 实例,我相信它是由 Owin 注入的(这是真的吗?):

public class GenericRepository<T> : IGenericRepository<T> where T : class
{
    private ApplicationDbContext context;

    public GenericRepository(ApplicationDbContext context)
    {
        this.context = context;
    }
}

但我不能对 UserManager 做同样的事情(它会抛出之前显示的错误):

public class AnunciosService : IAnunciosService
{
    private IGenericRepository<Anuncio> _repo;
    private ApplicationUserManager _userManager;

    public AnunciosService(IRepositorioGenerico<Anuncio> repo, ApplicationUserManager userManager)
    {
        _repo = repo;
        _userManager = userManager;
    }
}

控制器像这样使用 UserManager:

public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

我正在使用 ninject 来注入我的其他类,但是如何注入 UserManager 及其依赖项并避免在我的控制器中那样使用它?

【问题讨论】:

    标签: asp.net-mvc ninject asp.net-identity


    【解决方案1】:

    我是这样注入的

    kernel.Bind<IUserStore<ApplicationUser>>().To<UserStore<ApplicationUser>>();
    kernel.Bind<UserManager<ApplicationUser>>().ToSelf();
    

    现在它可以正常工作了。

    【讨论】:

    • 不错的解决方案。它也在我这边工作。谢谢。
    • 非常有帮助,谢谢。即使您回答了自己的问题,您也应该继续接受这个答案。
    • 你碰巧有一个工作代码示例吗?我已经为此苦苦挣扎了几个星期,似乎无法弄清楚。
    【解决方案2】:

    OP 的答案对我不起作用,因为我使用的是自定义 ApplicationUser 类,它以 long 而不是 string 作为键。

    因此,我创建了一个通用静态方法,它将从当前的 HttpContext 获取 OwinContext 并返回所需的具体实现。

    private static T GetOwinInjection<T>(IContext context) where T : class
    {
                var contextBase = new HttpContextWrapper(HttpContext.Current);
                return contextBase.GetOwinContext().Get<T>();
    }
    

    然后我使用GetOwinInjection这样的注入方法:

    kernel.Bind<ApplicationUserManager>().ToMethod(GetOwinInjection<ApplicationUserManager>);
    
    kernel.Bind<ApplicationSignInManager>().ToMethod(GetOwinInjection<ApplicationSignInManager>);
    

    如果你也在使用IAuthenticationManger,你应该像这样注入它:

    kernel.Bind<IAuthenticationManager>().ToMethod(context =>
                {
                    var contextBase = new HttpContextWrapper(HttpContext.Current);
                    return contextBase.GetOwinContext().Authentication;
                });
    

    【讨论】:

    • 好吧,我真的被卡住了,因为我的密钥是一个字符串并且 OP 的答案也不起作用,我得到了完全相同的异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多