views:

2724

answers:

5

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:

  1. 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?

  2. How do you think ObjectContext should be managed in ASP.NET MVC to both avoid lots of opening/disposing and prevent race conditions?

+2  A: 

I would use an IoC container like StructureMap, Autofac, Windosor, etc.

Todd Smith
+1  A: 

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.

gius
+4  A: 

Use the Repository pattern. Override Controller.Dispose to dispose the Repository, which, in turn, disposes the DataContext.

Craig Stuntz
A: 

Thanks for the IoC suggestion. I used Unity and implemented a per-request lifetime manager to store/retrieved objects via HttpContext.Current. Seems to work fine.

Buu Nguyen
Could you possibly post code to show how you added an object to HttpContext.Current? Did you add it to the Items collection, or ...?
Cynthia
This is the code in the custom Unity lifetime manager: HttpContext.Current.Items[key] = newValue
Buu Nguyen
+2  A: 

Using a single ObjectContext per request is a good idea.

If you are handling it yourself you need to put the context in the HttpContext.Items collection. On EndRequest you need to ensure that the context is disposed.

As mentioned, some IoC frameworks support this OTB - usually called PerRequest scope/lifetime.

Andrew Peters