Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to instantiate and dispose DbContext in MVC?

MVC 3 + EF 4.1

I'm choosing between two approaches to deal with DbContext:

  1. Instantiate in Application_BeginRequest, put it into HttpContext.Current.Items and dispose in Application_EndRequest.
  2. Create disposable UnitOfWork (kindof wrapper for DbContext) and start each controller action with using(var unitOfWork = new UnitOfWork()) { ... }

Share your experience please: Which one would you prefer? what are pros and cons for each approach?

like image 211
YMC Avatar asked Aug 08 '11 20:08

YMC


People also ask

Does DbContext need to be disposed?

As Daniel mentioned, you don't have to dispose the dbContext. From the article: Even though it does implement IDisposable, it only implements it so you can call Dispose as a safeguard in some special cases. By default DbContext automatically manages the connection for you.

How do I dispose of DbContext EF core?

When the controller is being disposed, call dispose on your repository and that should dispose the context. If you are using a service layer and not talking to the repository directly from the controller, then call dispose on the service which will call dispose on repo which will dispose the context.

What is the use of DbContext in MVC?

A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.


1 Answers

I would suggest you use a Dependency Injection framework. You can register your DbContext as per request

 container.RegisterType<MyDbContext>().InstancePerHttpRequest(); 

And inject it as a constructor parameter to the controller.

public class MyController : Controller {     public MyController(MyDbContext myDbContext)     {          _myDbContext = myDbContext;     } } 

If the registered type implements IDisposable then the DI framework will dispose it when the request ends.

1st approach: It is much more cleaner to use ID framework than manually implementing it. Further all your requests may not need your UoW.

2nd approach: The controller should not know how to construct your UoW(DbContext). Purpose is not reduce the coupling between components.

like image 170
Eranga Avatar answered Oct 04 '22 11:10

Eranga