5

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.

LaTeX
  • 1,411
  • 1
  • 17
  • 37

2 Answers2

8

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.

Dawson Toth
  • 5,580
  • 2
  • 22
  • 37
4

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.

Abdel Raoof Olakara
  • 19,223
  • 11
  • 88
  • 133
  • what is the drawback if I make use of a single instance of DbContext (or class derived from DbContext) for the entire application? – LaTeX Jan 31 '11 at 05:33
  • 2
    @Stack Overflow - read up on "singletons" in terms of database connections, and why it is evil. – RPM1984 Jan 31 '11 at 05:36