Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 812
LaTeX Avatar asked Jan 31 '11 05:01

LaTeX


People also ask

What is Application_Start in global ASAX?

Application_Start. The Application_Start event is fired the first time when an application starts. Session_Start. The Session_Start event is fired the first time when a user's session is started. This typically contains for session initialization logic code.

Why is global ASAX is used in MVC?

Effectively, global. asax allows you to write code that runs in response to "system level" events, such as the application starting, a session ending, an application error occuring, without having to try and shoe-horn that code into each and every page of your site.


1 Answers

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.

like image 134
Dawson Toth Avatar answered Sep 30 '22 11:09

Dawson Toth