What ninject binding should I use?

你离开我真会死。 提交于 2019-12-11 15:12:48

问题


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


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/21939051/what-ninject-binding-should-i-use

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!