The usual advice for using EF Core in a web application is to use a scoped DbContext per HTTP request. This is even the suggested default for web application in the Microsoft documentation. I recently encountered the argument that this is a bad idea and that you should not use DbContext as a scoped service as it will affect behaviour across your service boundaries. This seems to contradict the advice I usually read about this, but I do find the argument quite convincing in some aspects.
So the comparison here would be between injecting the DbContext as a scoped service and using a DbContextFactory and creating a new DbContext inside my classes every time I use the database.
The main argument against scoped DbContext is that the context has a state and what you do in other classes earlier can potentially affect code that runs later in a different class if it uses the same context. For example you might get cached entities from the context when you query the database, which can be unexpected and lead to different results.
Essentially the behaviour of your code can vary depending on what happened previously in the scope (the current HTTP request).
Having a context per request seemed natural at first, but I find the argument compelling that it kinda breaks the boundaries between my services if they share the context via DI. The more abstract question behind this is whether the unit of work is actually equivalent to the request or not.
Would always using context factories via DI make sense for an ASP.NET Core application and lead to a stronger decoupling of services? Sharing the context would still be possible, but explicit as a method parameter. You would not add the DbContext itself via DI at all. Or am I overthinking this and the context per request is still the best idea in most cases?