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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With