The static DbContext field in the Global.asax field compared to the field of the DbContext instance in the controller class?

Honestly, I am new to C # and Asp.net MVC. I also don't know how the asp.net web application runs on IIS and ASP.NET behind the scenes.

I am confused by the solution in which I have to declare a DbContext field (or any class derived from DbContext) in my asp.net mpc application.

I have two options:

  • Declare the field as a static field inside global.asax so that all controllers can use it.
  • Declare the field as an instance field inside each controller class.

Could you explain which one is correct? A more detailed explanation is really necessary.

+5
c # asp.net-mvc entity-framework
Jan 31 '11 at 5:25
source share
2 answers

If you make this a static field in global.asax, you will run into concurrency issues. Multiple threads from multiple requests can arrive and receive each other. To make matters worse, this will not be displayed until you start getting more traffic on your website or until you start stress testing. You will implement it as a singleton, everything will work well in your testing, and you will think: "I am a genius! See how pure this implementation is!" But someday you will be burnt by it, just like me. The results will be confused, users will begin to see data that does not belong to them, and the site will behave unexpectedly.

The context classes for both the Entity Framework and LINQ to SQL were designed as the lightweight instance that you configured for each set of queries that you want to run. He did not have to live long.

Check out this other question / answer on stack overflow on the same topic, differently.

+8
Jan 31 2018-11-11T00:
source share

You have to go with the second option. those. declare and use it in the controller. If you put DBContext as a static field in global.asax, you basically make it the only instance for the entire application.

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

+4
Jan 31 '11 at 5:30
source share



All Articles