ThatChris
ThatChris

Reputation: 752

Static Class Persistance in MVC Applications

I have over the last couple of months migrated my Webforms knowledge to MVC knowledge, and I have to say that after originally being an MVC skeptic I am loving MVC and the way it works.

The only thing I am still a bit unclear about is how static classes are persisted in MVC. In Webforms static class values were shared amongst the different clients accessing the application, which could lead to a user overwriting another users values should you decide to use static classes to save user related variables.

My first question is whether or not this is still the case in MVC?

Then my second question is about where to keep the DBContext instance in my MVC application. Currently I have it as a public variable in a static DAL class. The single context is then shared amongst all the clients.

The more I read about this the more I am starting to believe that this is the incorrect approach, but recreating the context inside each controller seems repetitive.

Is there a downside to having the Context in a static class?

Upvotes: 0

Views: 316

Answers (3)

musium
musium

Reputation: 3072

The DbConext is not thread safe, EF allows only one concurrtent operation on the same context. Therefore it is not a good idea to share it across requests. In the most cases a context per request is the best solution. (Hint: There are some IoC frameworks like autofac whichcan create instances per request)

Upvotes: 1

sachin
sachin

Reputation: 2361

Persisting a single DbContext instance across the lifetime of an application doesn't sound like a good idea to me. I usually use one DbContext instance per Request.

Following are 2 points that you might want to consider while deciding the appropriate lifetime for DbContext in your application:

  1. Re-using the same context for multiple Requests lets you benefit from the Cached entities and you could save many hits to the Database but you might then run into performance issues because you could end up having all your Database entities in memory at some time.

  2. Re-instantiating context too often on the other hand is also not recommended because it is an expensive operation.

You have to find a balance somewhere between these 2 approaches and for me, instantiating DbContext Per Request works best in most scenarios.

Upvotes: 1

Maarten
Maarten

Reputation: 22945

The context is supposed to be short-lived, so it might seem repetitive, but yes, create a context inside each controller. Use a single context per request to be precise.

Upvotes: 1

Related Questions