views:

112

answers:

2

Its not One is it? I have a method that gets five Lists from different repositories. Each call opens and closes a new Datacontext. Is this ok to do or should I wrap everything in One datacontext. In this case it is not straightforward to use the same datacontext, but i am afraid that opening and closing numerous datacontext in one page request is not good.

+2  A: 

Here is an article on just that subject...

Linq to SQL DataContext Lifetime Management

He recommends one per request and I have implemented that pattern in a few applications and it has worked well for me.

He talk a little about that in is article... His quick and dirty version makes a reference to System.Web and does something like this:

 private TDataContext _DataContext;

 public TDataContext DataContext
 {
  get
  {
   if (_DataContext == null)
   {

    if (HttpContext.Current != null)
    {
     if (HttpContext.Current.Items[DataContextKey] == null)
     {
      HttpContext.Current.Items[DataContextKey] = new TDataContext();
     }

     _DataContext = (TDataContext)HttpContext.Current.Items[DataContextKey];
    }
    else
    {
     _DataContext = new TDataContext();
    }
   }

   return _DataContext;
  }
 }

But then he recommends you take the next step and get rid of the reference to System.Web and use dependency injection and create your own IContainer that could determine the life span of your datacontext based on whether your running in unit test, web application, etc.

Example:

public class YourRepository
{

    public YourRepository(IContainer<DataContext> container)
    {

    }

}

then replace HttpContext.Current.Items[DataContextKey] with _Container[DataContextKey]

hope this helps...

J.13.L
if i create one datacontext in the business layer, how to properly pass datacontext to each repository that i access?
zsharp
via dependency injection
Todd Smith
A: 

I use on Unit of Work per request and built a IHttpModule that manages unit of work lifecycle, creating it on request and diposing it afterwards. The current unit of work is stored in HttpContext.Current.Items (hidden in Local.Data).

Nigel Sampson