Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
add comment

5 Answers

up vote 1 down vote accepted

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

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.

share|improve this answer
    
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 Aug 26 '10 at 19:40
    
This is the code in the custom Unity lifetime manager: HttpContext.Current.Items[key] = newValue –  Buu Nguyen Aug 27 '10 at 5:06
add comment

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

share|improve this answer
add comment

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.