5

There are lots of questions about these subjects separately and everyone have their own opinion. Maybe someone can give me a good answer regarding the following issue.

I have an Asp.NET MVC web service which uses EntityFramework for accessing the DB. There's a single controller and an instance of it is created each time a user makes a request to the web service. Every request is fast. It just gets some data from DB, changes it and then saves it.

The question of course is how to maintain the DbContext (since it's not thread safe)? On the ctor of the controller i create an instance of DbContext. On the Dispose() of the controller I Dispose the DbContext.

I've seen on some posts that it's not a good practice to create an instance per every request. Isn't it?

Thanks, Edi.

Edi
  • 969
  • 3
  • 9
  • 20

2 Answers2

4

The DbContext is designed to be instantiated with each request. It implements IDisposable and instantiating is a low-cost operation. Connection pooling to the database is handled internally.

More Information:

Entity Framework and Connection Pooling

Community
  • 1
  • 1
Dave Swersky
  • 34,502
  • 9
  • 78
  • 118
  • Great, now I understand. I used to programming ADO where I handled the connection pooling by myself, and I was confused when I switch to the DbContext concept. – Edi Dec 13 '12 at 21:29
  • I just need to point out to you Edi and anyone coming after that needs to go to the raw ADO.Net level for some reason that Connection Polling is handled already for you lower in the stack by windows (and the DAC) itself. There's generally no need to attempt to implement that type of logic yourself unless you're trying to introduce some type of throttled pool (and even then, there's easier ways to go about it with a container of some type) – Jimmy Zimms Aug 25 '15 at 12:41
2

The DbContext is a very light object and it is designed to be created for each operation (=request) and then disposed. Under the hood ado.net takes care of reusing db connection from connection pool.

Z .
  • 12,657
  • 1
  • 31
  • 56