Is it safe to store an ObjectContext in a thread static variable in ASP.NET?

.net, asp.net, entity-framework, mef, thread-safety

Solution

No, there can be multiple requests in the same thread and, more importantly, one request can be processed in multiple threads. This is called thread agility, and you will run into problems when you store stuff in thread-static variables instead of the Context: When ASP.NET moves from one thread to another during the same request, the HttpContext is still accessible, but the thread-static variable is not.

Some links with further information:

- CallContext vs ThreadStatic (related question)

- http://piers7.blogspot.com/2005/11/threadstatic-callcontext-and_02.html (blog entry with details)

Problem

I've read that I should store an `ObjectContext` in `HttpContext.Current` in order to share my `ObjectContext` across different services/repositories that are called in a request. I'm wondering if it is safe to use an `ObjectContext` with the `[ThreadStatic]` attribute on a `static` class variable instead. Is that a safe thing to do? Is each request processed in its own thread?

Original source

Related problems