Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Dependency Injection with Entity Framework DbContext?

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?

like image 632
omkarshukla Avatar asked Feb 29 '16 09:02

omkarshukla


People also ask

Which method allows us to register the DbContext as a dependency?

The AddDbContext extension method registers DbContext types with a scoped lifetime by default.

What is dependency injection in Entity Framework?

About @yogihosting. Dependency Injection with Entity Framework Core. ASP.NET Core has an excellent Dependency Injection feature through which this framework provides you with an object of any class that you want. So you don't have to manually create the class object in your code.

Is DbContext scoped or Singleton?

First, DbContext is a lightweight object; it is designed to be used once per business transaction. Making your DbContext a Singleton and reusing it throughout the application can cause other problems, like concurrency and memory leak issues.

What is EF DbContext?

DbContext is a combination of the Unit Of Work and Repository patterns.” In simplified way we can say that DbContext is the bridge between Entity Framework and Database. Whatever we are doing in Entity Framework (get data, save data, fetch data or any other opration) is done via DbContext.


1 Answers

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.
        container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

        // This is an extension method from the integration package as well.
        container.RegisterMvcIntegratedFilterProvider();

        container.Verify();

        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);
    }
}
like image 144
Szer Avatar answered Nov 15 '22 11:11

Szer