How to use Dependency Injection with Entity Framework DbContext? c# entity-framework


I am currently working on including a new functionality for a Website.

I have a DbContext class which I created using EF6.

The website uses a Master Layout in which sublayouts are rendered depeding upon the page requested. I want to use Dependency Injection to access the DbContext in the Sublayouts. Generally, I would use a Controller to handle the calls, however, I want to skip that in this case.

Also, I want to keep the implementation flexible so that new DbContexts are added I will be able to use them easily.

I was thinking of creating an interface "IDbContext".

I will have the new interface(let's say "IRatings") implementing this interface.

Am I going about it the right way?

Any thoughts?

2/29/2016 9:50:58 AM

Accepted Answer

I am prefer SimpleInjector but it wont differ that much for any other IoC container.

More info here

Example for ASP.Net4:

// You'll need to include the following namespaces
using System.Web.Mvc;
using SimpleInjector;
using SimpleInjector.Integration.Web;
using SimpleInjector.Integration.Web.Mvc;

    // This is the Application_Start event from the Global.asax file.
    protected void Application_Start()
        // Create the container as usual.
        var container = new Container();
        container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

        // Register your types, for instance:
        container.Register<IDbContext, DbContext>(Lifestyle.Scoped);

        // This is an extension method from the integration package.

        // This is an extension method from the integration package as well.


        DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

Such registration will create DbContext per every WebRequest and close it for you. So you simply need inject IDbContext in your controller and use it as usual without using:

public class HomeController : Controller
    private readonly IDbContext _context;

    public HomeController(IDbContext context)
        _context = context;

    public ActionResult Index()
        var data = _context.GetData();
        return View(data);
3/1/2016 11:57:53 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow