开发者

Static field of DbContext in Global.asax versus instance field of DbContext in controller class?

开发者 https://www.devze.com 2023-02-07 20:19 出处:网络
Frankly I am a newbie in both C# and Asp.net MVC. I also do not know how the asp.net web application actually works on IIS and ASP.NET framework behind the scene.

Frankly I am a newbie in both C# and Asp.net MVC. I also do not know how the asp.net web application actually works on IIS and ASP.NET framework behind the scene.

I am confused with the decision where I have to declare a field of DbContext (or any class derived from DbContext) in my asp.net mvc application.

I have two choices:

  1. Declare the field a开发者_开发技巧s a static field inside global.asax such that all controllers can make use of it.
  2. Declare the field as an instance field inside each controller class.

Could you explain which one is the correct one? More detailed explanation is really needed.


If you make it a static field in global.asax, you will run into concurrency problems. Multiple threads from multiple requests can come in and get each other's data. What's worse is that this will not show up until you start getting more traffic on your website, or until you start load testing. You'll implement it as a singleton, all will be working well in your testing, and you'll think, "I'm a genius! Look how clean this implementation is!" But someday, you will be burned by this, as I have been. Results will get mixed up, users will start seeing data that doesn't belong to them, and the website will behave unexpectedly.

The context classes for both Entity Framework and LINQ to SQL were designed to be a lightweight instantiation, something you set up for each set of queries you want to run. It's not meant to be long lived.

Check out this other Stack Overflow question / answer on the same topic, worded differently.


You should go with the second option. ie declare and use it in the controller. If you put the DBContext as a static field in global.asax, you are basically making it a single instance for the entire application.

On the other hand, with the second option you have a DBcontext for each request. It would be better if you can use a dependency injection to get the DBContext in each action method.

0

精彩评论

暂无评论...
验证码 换一张
取 消