DataContext、LinqToSql 的生命周期
我在互联网上找到了一篇介绍如何实现存储库模式的文章。实现看起来与这里类似:
class ProductRepository : IProductRepository
{
var context;
public ProductRepository() {
this.context = new MyDataBaseDataContext();
}
// the rest of methods
}
但我不太确定这是对的,上下文发生了什么?垃圾收集器是否会处理该对象?或者更好的是我应该使用 using (...) { } 语句创建上下文?
I have found on the Internet an article which presents how to implement repository pattern. The implementation looks similar like here:
class ProductRepository : IProductRepository
{
var context;
public ProductRepository() {
this.context = new MyDataBaseDataContext();
}
// the rest of methods
}
But Im not quite sure is this right, what is happened with context? Is the Garbage Collector dispose this object? Or better should I create context with using (...) { } statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Repository
不应打开数据上下文,DataContext
必须传递给它 - 因为它不能拥有它。 假设您有一个操作需要在事务中进行并且涉及多个存储库,您会怎么做?您需要使用
UnitOfWork
模式。在此模式中,
UoW
(包装DataContext
)被传递到存储库。实际上,业务层中的
ProductManager
创建了一个工作单元
。Repository
should not open a data context,DataContext
must be passed to it - since it must not own it. Let's say you have an operation which needs to be in a transaction and involves multiple repositories, what would you do?You need to use
UnitOfWork
pattern.In this pattern, a
UoW
(which wraps aDataContext
) is passed to a repository.Practically,
ProductManager
in Business layer creates aUnit Of Work
.这个问题的简单答案是,存储库应该确保自行处理数据上下文,而不是让它由 .NET 运行时最终确定。这可以通过遵循标准 .NET 处置模式来实现...
The simple answer to this question is that the repository should be sure to dispose the data context itself, rather than letting it be finalized by the .NET runtime. This can be achieved by following the standard .NET dispose pattern...
我想这取决于您是否需要跨存储库操作的事务以及跟踪更改的需要。数据 datacontext 非常有用,因为它可以让您检索一堆对象,在应用程序中修改它们,然后在您认为合适的任何时候简单地调用 SubmitChanges /RollbackChanges。但是,如果您不在存储库中公开此功能,您可能最好在每个存储库方法中“使用”一个实例,因为这将保留用于跟踪更改的内存使用和资源。
I guess it depends on whether you need transactions across repository operations and your need for tracking changes. The data datacontext can be immensely helpful since it can let you retrieve a bunch of objects, modify them in the application and then simply call SubmitChanges /RollbackChanges at any time you see fit. But if you don't expose this functionality in your repository you are probably better off by just "using" an instance in each repository method since this will preserve memory usage and resources for tracking changes.