Unity and Entity Framework

Jun 12, 2012 at 10:31 AM

Hey,

I have tried to implement Unity.Mvc3 in to my solution to deal with disposing of entity framework context. The problem I get though is that when two Async processes hit at the same time, the context connection get confused and one ends up not being able to open.

Have you done anything around the EF within TecX?

Nick

Coordinator
Jun 12, 2012 at 11:06 AM

Hi,

I prefer not to use EF whenever possible. I worked with it in several projects and it was such a PITA that I just gave up on it.

DbContext and ObjectContext are not thread-safe. Thus it will always be a problem if you share the same instance of a context across incoming requests.

The HierarchicalLifetimeManager is mostly the same as the ContainerControlledLifetimeManager so your context will have a singleton lifetime but should be disposed when the (child) container that was used to create it gets disposed (as is done inside their custom HttpModule). For an overview of the built-in LifetimeManagers have a look at this post.

I'm not sure how good or bad Unity.Mvc3 is at handling multi-threading. I'm not a multi-threading guru myself. But if something goes wrong with the creation of child containers for each new request you might end up with a shared container which returns some shared instance of the context.

In short: I can't really help you here, sorry.

Btw: LifetimeManagers that clean up after themselves are on the wish-list for Unity vNext

Sebastian

Jun 13, 2012 at 11:15 AM

Hi Seb,

Thanks for the heads up. I found out a way to get it working in the end, it looked like I was doing a resolve in the wrong place which meant the context was sitting in a different lifetime manager, and hence, never getting disposed of.

One last question, how would you see Lifetime Manager looking if you wanted to have that object last for the entire session of a user?

Cheers, Nick

Coordinator
Jun 13, 2012 at 11:26 AM

There are samples out there that show various flavours of an HttpContext-backed LifetimeManager (one can be found in TecX.Web.Unity as well). That would give you a per request lifetime. If you want per session lifetime you should be able to switch from HttpContext.Current.Items to HttpContext.Current.Session.Items as the backing store.

A problem that might occur is what happens when the SessionState gets dehydrated (e.g. persisted in a database) or you have a Web farm and the state needs to be transfered to another machine. The class UnityContainer is not serializable which will cause serious trouble as soon as the ASP.NET infrastructure tries to serialize the contents of the SessionState for one of the above reasons.