Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is DbContext per-request?

There are other similar SO questions out there, but none that really answer my specific question:

If an MVC controller is created for every request then what is the advantage of DbContext being per-request (assuming I’m injecting it into the controller)? Wouldn’t transient achieve the same result?

For example, say I have a data entry/edit form - the controller would have a ‘get’ method to retrieve the entity to be edited from the db, and a ‘post’ method to save back to the db (this would involve retrieving the entity again, update the changed values, then SaveChanges). Get and Post are separate requests, so I don’t see how a per-request DbContext helps here.

What am I missing? In what scenarios is a per-request DbContext useful?

like image 257
Andrew Stephens Avatar asked Jun 18 '26 15:06

Andrew Stephens


2 Answers

Wouldn’t transient achieve the same result?

Yes, but that's only if you know for sure that the only Resolve<DbContext>() call is in your controller (preferably through constructor injection), and from there the instance is being passed on to another layers.

Obviously, that's not always the case.

There can always be another "resolving points" in your code (MVC filters, service layers called indirectly, or even code that uses IoC in Service Locator mode), and in those case you typically would want to ensure the use of the same DbContext instance throughout the HTTP request.

like image 177
haim770 Avatar answered Jun 21 '26 07:06

haim770


In addition to @haim770s answer:

Why is DbContext per-request?

One of the reasons why Transient might be not suited is that you'll get a new DbContext for every service/repository/command/query or UnitOfWork object you create or request.

If you cascade some updates, ensuring 1 DbContext per request, makes it easier to rollback all these updates, e.g. as an transaction or UnitOfWork - per request.

like image 45
Stefan Avatar answered Jun 21 '26 06:06

Stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!