Linq to SQL存储库是否应实现IDisposable [英] Should Linq to SQL repository implement IDisposable

查看:53
本文介绍了Linq to SQL存储库是否应实现IDisposable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的几天里,我一直在与Linq一起研究大量的存储库模式.那里有很多信息,但通常是矛盾的,我仍在寻找确切的信息来源.

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.

我仍然不确定的一件事是存储库是否应该实例化它自己的DataContext并具有SubmitChanges方法,或者是否应该注入DataContext并在外部处理提交.我已经看过这两种设计,但对推理没有真正的评论.

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() { ... }
}

所以我的主要问题是,使用上述实现,为什么存储库不需要实现IDisposable?我确实看到了上面的数百个示例,但似乎都没有人去理会DataContext.这不是内存泄漏吗?

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?

推荐答案

如果将autoclose设置为false,则处置DataContext会关闭基础连接.如果不调用dispose,则必须等待让GC为您调用.您应该实现IDisposable并处置存储库,而储存库又应处置其DataContext.

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.

另一种解决方案是,如果您的方法无法在单个事务中协同工作,则为存储库中的每个方法创建一个新的数据上下文.然后,您可以通过using()指令在使用上下文后立即对其进行处置.

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.

这篇关于Linq to SQL存储库是否应实现IDisposable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆