Search code examples
asp.net-mvcninjectasp.net-identity

How do I inject Identity classes with Ninject?


I'm trying to use UserManager in a class, but I'm getting this error:

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

I'm using the default Startup.cs, which sets a single instance per request:

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

I'm able to get the ApplicationDbContext instance, which I believe is getting injected by Owin (Is that true?):

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

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

But I can't do the same with UserManager (It throws the error shown before):

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

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

The controller uses the UserManager like this:

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

I'm using ninject to inject my other classes, but how do I inject the UserManager with it's dependencies and avoid using it like that in my controllers?


Solution

  • I injected It like this

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

    And now It's working as it should.