在ASP.NET MVC5中使用Ninject注入实体框架DbContext

时间:2016-12-27 15:11:09

标签: entity-framework asp.net-mvc-5 ninject

我刚刚进入依赖注入世界。

我有以下自定义DbContext -

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

想在此基本控制器中注入SkyTrackerContext -

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

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

样本用法 -

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

我应该在NinjectWebCommon.cs中写什么来注入这个上下文?

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 个答案:

答案 0 :(得分:5)

首先,你应该避免方法注入。相反,使用构造函数注入。换句话说:

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

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

    ...
}

然后,就Ninject配置而言,它非常简单:

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