Linq to SQL 存储库是否应该实现 IDisposable
在过去的几天里,我一直在使用 Linq 谷歌搜索大量有关存储库模式的信息。那里有很多信息,但它们往往是矛盾的,我仍在寻找明确的来源。
我仍然不确定的一件事是存储库是否应该实例化它自己的 DataContext 并具有 SubmitChanges 方法,或者是否应该注入 DataContext 并在外部处理提交。我看过这两种设计,但没有对其推理进行真正的评论。
无论如何,以下模式非常常见
class Repository<T>
{
DataContext db = new LinqDataContext();
public IEnumerable<T> GetAll() { ... }
public T GetById() { ... }
... etc
public void SubmitChanges() { ... }
}
所以我的主要问题是,通过上述实现,为什么存储库不需要实现 IDisposable?我已经看到了上面数百个示例,但它们似乎都没有费心处理 DataContext。这不是内存泄漏吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您将 autoclose 设置为 false,则处置 DataContext 会关闭底层连接。如果您不调用 dispose,则必须等待 GC 为您调用它。您应该实现 IDisposable 并处置您的存储库,而存储库又应处置其 DataContext。
另一个解决方案是,如果您的方法不能在单个事务中协同工作,则为存储库中的每个方法创建一个新的数据上下文。然后,您可以在通过 using() 指令使用上下文后立即处理它们。
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.
没有必要但你可能应该实现
IDisposable
。Not necessary but you probably should implement
IDisposable
.