Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

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

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 as 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...