Inject Entity Framework DbContext using Ninject in

2019-07-19 17:07发布

问题:

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