Inject Entity Framework DbContext using Ninject in ASP.NET MVC5

≡放荡痞女 提交于 2019-12-24 01:24:32

问题


I have just landed in dependency injection world.

I have the following custom DbContext-

public partial class SkyTrackerContext: DbContext
{
    public SkyTrackerContext(): base()
    {
        Database.SetInitializer(new SkyTrackerDBInitializer());
    }
}

Would like inject SkyTrackerContext in this base controller-

public abstract class BaseController : Controller
{
    public BaseController() {}

    [Inject]
    public SkyTrackerContext MyDbContext { get; set; }
 }

Sample usage-

public class LoginController : BaseController
{            
    public ActionResult ValidateLogin(Login login) 
    {
      var query = MyDbContext.Persons.Where(.....);
    }
}

What should I write in NinjectWebCommon.cs to inject this context ?

private static IKernel CreateKernel()
{
    var kernel = new StandardKernel();
    try
    {
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);
        return kernel;
     }
     catch
     {
         kernel.Dispose();
         throw;
     }
}

回答1:


First, you should avoid method injection. Instead, use constructor injection. In other words:

public abstract class BaseController : Controller
{
    protected readonly DbContext context;

    public BaseController(DbContext context)
    {
        this.context = context;
    }

    ...
}

Then, as far as the Ninject config goes, it's extremely simple:

kernel.Bind<DbContext>().To<SkyTrackerContext>().InRequestScope();


来源:https://stackoverflow.com/questions/41347607/inject-entity-framework-dbcontext-using-ninject-in-asp-net-mvc5

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