views:

102

answers:

2

I've been googling a ton on repository patterns with Linq over the last few days. There's a lot of info out there but it's often contradictory and I'm still looking for a definitive source.

One of the things I'm still not sure about is whether the repository should instantiate it's own DataContext and have a SubmitChanges method, or if the DataContext should be injected and the submission handled externally. I've seen both designs but no real comment on the reasoning.

Anyway, the following pattern is pretty common

class Repository<T>
{
    DataContext db = new LinqDataContext();

    public IEnumerable<T> GetAll() { ... }
    public T GetById() { ... }

    ... etc

   public void SubmitChanges() { ... }
}

So my main question is, with the above implementation, why does the repository not need to implement IDisposable? I've seen literally hundreds of examples as above, and none of them seem to bother disposing the DataContext. Isn't this a memory leak?

+1  A: 

Not necessary but you probably should implement IDisposable.

Darin Dimitrov
+1  A: 

Disposing a DataContext closes the underlying connection if you have autoclose set to false. If you do not call dispose, you have to wait for the GC to call it for you. You should implement IDisposable and dispose of your repositories which should in turn dispose their DataContext.

Another solution is to create a new data context for each method in your repository if your methods don't work together within a single transaction. Then you can dispose your contexts as soon as they are used via a using() directive.

BC
If you close the datacontext, then you can't submit any changes you have made to your returned objects. Is that correct? Or can a new context still work out which items are dirty?
fearofawhackplanet
Each instance has it's own state. When you dispose the DataContext, it frees the object cache that is used to track changes.
BC
MSDN states: In general, a DataContext instance is designed to last for one "unit of work" however your application defines that term. A DataContext is lightweight and is not expensive to create. A typical LINQ to SQL application creates DataContext instances at method scope or as a member of short-lived classes that represent a logical set of related database operations.
BC