Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc 4 - Okay to share DbContext per thread?

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 threads. But how about sharing it across non-concurrent web requests?

Due to thread agility (What is the meaning of thread-agility in ASP.Net?), am I right that a thread can handle more than one web request before it dies?

If so, is it safe to dependency inject a DbContext instance for each thread?

Reason for this is I'm using Unity, which does not include per-request lifetime option. From MVC, EF - DataContext singleton instance Per-Web-Request in Unity , I think I could use a custom LifetimeManager; I'm just wondering if it is safe and sufficient to use PerThreadLifetimeManager.

like image 787
user1501961 Avatar asked Nov 01 '13 07:11

user1501961


People also ask

Is EF DbContext thread safe?

DbContext is not thread-safe. Do not share contexts between threads. Make sure to await all async calls before continuing to use the context instance. An InvalidOperationException thrown by EF Core code can put the context into an unrecoverable state.

Should DbContext be a singleton?

Popular Answer. DbContext should not be used as a singleton because it is holding a connection object which cannot be used by multiple threads at the same time. You will run into errors if two requests try to use it at the same time. If your service depends on the context, the service cannot be a singleton.

Why do we use DbContext in MVC?

DbContext is a class provided by Entity Framework to establish connection to database, query the db and close connection. Extending DbContext permits to define database model with DbSet (specific Set mapped to a table or more), create a database, query a database...


2 Answers

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;
})); 
like image 143
Steven Avatar answered Oct 12 '22 23:10

Steven


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.

like image 30
Peter Kiss Avatar answered Oct 13 '22 00:10

Peter Kiss