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, w开发者_JAVA百科ith 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?
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.
Not necessary but you probably should implement IDisposable
.
精彩评论