views:

37

answers:

2

Hi,

I was just wondering how long should a DataContext really live. All the patterns and practices books like Dino Esposito's Microsoft .NET: Architecting Applications for the Enterprise tell you, datacontext must not live long, nor should it be cached. But how long is the right time? A whole web request, a unit of work, a transaction, only one query at a time? (I assume a web request has usually more than just one unit of work)

Lets say you use the Entity Framework as a ORM Tool in a web application. But what about the Identity Map Pattern in this scenario. Lets say you've got a dedicated instance of a Customer DAL, which creates a Datacontext and another Invoice DAL, which it self creates a new DataContext for its purpose as well. If you would have gotten a base class for all DALs, that creates a single instance of the ObjectContext and dispose this one at the end. Would that be considered a bad implementation? It could make sense to just have one ObjectContext for a single web request, in my opinion. It could make use of the supported Identity Map Pattern by the Entity Framework as just one advantage.

Any ideas, comments, thoughts or criticism?

+1  A: 

The simplest thing to do is dispose of the DataContext as soon as possible. That said you can keep the DataContext around as long as you want, as long as you are willing to deal with the headaches that will cause.

Like many things, the answer is "it depends" and is situation dependent. There is no single answer.

For web apps, keeping a DataContext around for the life of a web request is generally pretty straight forward to deal with.

I would suggest you start with small lifetimes and then increase the lifetime in situations where you need the caching and other benefits of longer life DataContexts.

Michael Maddox
A: 

Alex James wrote a good article about this. In it, he notes you need to consider:

  • Disposal
  • Cost Of Construction
  • Memory Usage
  • Thread Safety
  • Statelessness
  • Natural finite lifetimes
Craig Stuntz