MVC, DbContext and Multithreading

点点圈 提交于 2019-11-28 04:33:59

问题


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.


回答1:


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




回答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.



来源:https://stackoverflow.com/questions/13868264/mvc-dbcontext-and-multithreading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!