Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC, DbContext and Multithreading

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.

like image 522
Edi Avatar asked Dec 13 '12 20:12

Edi


2 Answers

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

like image 199
Dave Swersky Avatar answered Sep 30 '22 07:09

Dave Swersky


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.

like image 38
Z.D. Avatar answered Sep 30 '22 05:09

Z.D.