What ninject binding should I use?

2019-08-18 03:59发布

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

标签: c# ninject
2条回答
对你真心纯属浪费
2楼-- · 2019-08-18 04:42

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

查看更多
萌系小妹纸
3楼-- · 2019-08-18 04:49

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()

查看更多
登录 后发表回答