One DbContext per web request... why?

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

One DbContext per web request... why?

Message par ForumBot »

One DbContext per web request... why?
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: One DbContext per web request... why?

Message par ForumBot »

NOTE: This answer talks about the Entity Framework's `DbContext`, but
it is applicable to any sort of Unit of Work implementation, such as
LINQ to SQL's `DataContext`, and NHibernate's `ISession`.

Let's start by echoing Ian: Having a single `DbContext` for the whole application is a Bad Idea. The only situation where this makes sense is when you have a single-threaded application and a database that is solely used by that single application instance. The `DbContext` caches data, and it gets stale pretty soon. This will get you in all sorts of trouble when multiple users or application instances work on that database through the use of the `DbContext` (which is very common of course).

But I expect you already know that and just want to know why not to just inject a new instance (i.e. with a transient lifestyle) of the `DbContext` into anyone who needs it. (for more information about why a single `DbContext` -or even on context per thread- is bad, read [this answer](https://stackoverflow.com/a/3266481/264697)).

Let me start by saying that registering a `DbContext` as transient *could* work, but typically you want to have a single instance of such a unit of work within a certain scope. In a web application, it can be practical to define such a scope on the boundaries of a web request; thus a Per-Web-Request lifestyle. This allows you to let a whole set of objects operate within the same context. In other words, they operate within the same business transaction.

If you have no goal of having a set of operations operate inside the same context, in that case the transient lifestyle is fine, but there are a few things to consider:

- As every object gets its own instance, every class that changes the state of the system, needs to call `_context.SaveChanges()`. Otherwise changes would get lost, because every `DbContext` instance has its own set of changes. This can complicate your code, and adds a second responsibility to the code (the responsibility of controlling the

*(Réponse tronquée)*
Répondre

Revenir à « .NET & C# »