Maximum "units of work" per request per page?
Isn't this one? 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 easy to use the same data file, but I am afraid that opening and closing a lot of datacontext in one page request is not very good.
a source to share
Here is an article on this topic ...
Linq to SQL DataContext Lifetime Management
He recommends on one request and I have applied this pattern across multiple applications and it worked great for me.
He talks about it a bit in the article ... His quick and dirty version links 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 that you take the next step and get rid of the System.Web reference and use dependency injection and create your own IContainer that could determine the lifespan of your datacontext based on whether your run in a unit test, a web application and etc.
Example:
public class YourRepository
{
public YourRepository(IContainer<DataContext> container)
{
}
}
then replace HttpContext.Current.Items[DataContextKey]
with_Container[DataContextKey]
hope this helps ...
a source to share