Should Linq to SQL repository implement IDisposable

旧时模样 提交于 2019-12-06 08:54:38

问题


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:


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.




回答2:


Not necessary but you probably should implement IDisposable.



来源:https://stackoverflow.com/questions/2975760/should-linq-to-sql-repository-implement-idisposable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!