public AccountController(IUserStore<ApplicationUser> userStore)
{
//uncommenting the following line, uses the correct context, but
//unit testing fails to work, as it is overwritten, so I need to use IoC
//to inject
//userStore = new UserStore<ApplicationUser>(new ApplicationDbContext());
UserManager = new UserManager<ApplicationUser>(userStore);
What should my ninject binding look like? The only thing that I could get to even compile looks like the following, but that is not getting the correct context.
kernel.Bind<IUserStore<ApplicationUser>>().To<UserStore<ApplicationUser>>();
which is binding to something, but not the correct context used in the commented out line
Try using a ConstructorArgument
kernel.Bind<IUserStore<ApplicationUser>()
.To<UserStore<ApplicationUser>>()
.WithConstructorArgument(new ConstructorArgument("context", new ApplicationDbContext())
But...
In reality, you should also inject the dependency in your UserStore<ApplicationUser>
, by binding ApplicationDbContext
. The framework will then construct the whole graph for you:
kernel.Bind<ApplicationDbContext>().ToSelf()
From cvbarros answer we came up with the following:
kernel.Bind<ApplicationDbContext>().ToSelf().InRequestScope();
kernel.Bind<IUserStore<ApplicationUser>>()
.To<UserStore<ApplicationUser>>()
.WithConstructorArgument("context", context => kernel.Get<ApplicationDbContext>());
This allows the ApplicationDbContext
to be injected and/or the UserManager
to be injected. It also allows the UserManager
to get the ApplicationDbContext
from the dependency injector instead of creating a new instance.
Note, this code goes in the /App_Start/NinjectWebCommon.cs file