From One DbContext per web request... why?
My understanding is that a DbContext instance should not be shared across concurrent web request, so definitely not across thr
If you will use multiple DbContext per request you can end up with a multi threaded application with high possibility loosing data integrity. One web request can be viewed as one transaction ; but with PerThreadLifeTimeManager you would have multiple distinct transactions which aren't related but maybe they should. For example posting a form with many data can end up with saving multiple database table and with 2 or more independent context can happen that one insert succeeds but another fails and you could have inconsistent data.
The other important thing is that the ASP.NET infrastructure uses thread pooling so every started thread will be reused after the request has finished and if something went wrong in one request it can affect another one. That is why not recommended to use any Thread-LocalStorage (static in the thread) in threadpool environment because we can not control the threads' lifetime.
is it safe to dependency inject a DbContext instance for each thread?
It depends. If your idea is to have one DbContext
per web request, and the consistency of your application depends on it, having one DbContext
per thread is a bad idea, since a single web request can still get multiple DbContext instances. And since ASP.NET pools threads, instances that are cached per thread, will live for the duration of the entire application, which is very bad for a DbContext
(as explained here).
On the other hand, you might be able to come up with a caching scheme that ensures that a single DbContext
is used for a single web request, and is returned to a pool when the request is finished, so other web requests could pick it up. This is basically the way how connection pooling in .NET works. But since DbContext
instances cache data, that data becomes stale very quickly, so even if you are able to come up with a thread-safe solution, your system still behaves in an inconsistent way, since at some seemingly random moments, old data is shown to the user, while in a following request new data is shown.
I think it is possible to clear the DbContext
's cache at the beginning of a web request, but that would be basically be the same as creating a new DbContext
for that request, but with the downside of much slower performance.
I'm just wondering if it is safe and sufficient to use PerThreadLifetimeManager.
No, it isn't safe because of the reasons described above.
But it is actually quite easy to register a DbContext on a per-web request basis:
container.Register<MyApplicationEntities>(new InjectionFactory(c => {
var context = (MyApplicationEntities)HttpContext.Current.Items["__dbcontext"];
if (context == null) {
context = new MyApplicationEntities();
HttpContext.Current.Items["__dbcontext"] = context;
}
return context;
}));