I’m using ADO.NET EF in an MVC application. I’m considering putting the ObjectContext inside HttpContext.Current so that all logic in the same request can access to it without having to open/destroy each time. However, I’m really sure if it’s a good way to manage ObjectContext instances. I have 2 questions regarding this need:
-
As HttpContext.Current property is backed by a thread-local field and ASP.NET uses threads from pool to handle requests, is it possible that an ObjectContext instance put into HttpContext.Current by a request will be visible to a subsequent request running on the same thread from the pool?
-
How do you think ObjectContext should be managed in ASP.NET MVC to both avoid lots of opening/disposing and prevent race conditions?
I agree with Todd – use DI/IoC cotnainer (Unity, Windsor) with per-thread (or custom per-request) lifetime.
Ad 2, as I remember, in Linq to SQL, DataContext object was considered a lightweight object so it should not be a problem to create it often. Hopefully, it is similar for EF.