我应该处置 EF4.0 ObjectContexts 吗?
我有一个与 Entity Framework 4 配合使用的简单 UnitOfWork
模式,如下所示:
public class UnitOfWork
{
private readonly myEntities _context;
public UnitOfWork()
{
_context = new myEntities();
}
public myEntities Context { get { return _context; } }
public void SaveChanges()
{
_context.SaveChanges();
}
public void Finish()
{
_context.Dispose();
}
}
我的问题是:我需要那个 Finish
方法吗?我是否需要在 ObjectContext
派生的实体对象上显式调用 Dispose
,还是应该让垃圾收集器来处理它?
I've got a simple UnitOfWork
pattern going with Entity Framework 4, like so:
public class UnitOfWork
{
private readonly myEntities _context;
public UnitOfWork()
{
_context = new myEntities();
}
public myEntities Context { get { return _context; } }
public void SaveChanges()
{
_context.SaveChanges();
}
public void Finish()
{
_context.Dispose();
}
}
My question is this: do I need that Finish
method? Do I need to explicitly call Dispose
on my ObjectContext
-derived entity object, or should I just let the garbage collector take care of it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于 EF 上下文是一次性的,并且其核心代表数据库连接,所以您应该
Dispose()
它。为了让
UnitOfWork
类的使用者更容易一些,我会让它实现IDisposable
而不是提供Finish()
> 方法。这样它就可以在using
块中使用。Since the EF context is disposable and at its core represents a database connection yes, you should
Dispose()
it.To make it a little easier on the consumers of your
UnitOfWork
class, I would make it implementIDisposable
as well as opposed to providing aFinish()
method. That way it can be used in ausing
block.