我正在使用 Entity Framework 4,并且创建了一个 UnitOfWork 类,该类创建我的 Context 并通过公共属性将其公开为 IContext 接口。Context 类继承自 ObjectContext 并将我的 Poco 实体公开为公共属性,例如
public IObjectSet<User> Users
{
get { return _users ?? (_users = CreateObjectSet<User>("Users")); }
}
private IObjectSet<User> _users;
我还创建了一些存储库类,它们将该上下文作为构造函数参数,并在存储库类中执行查询时使用该上下文。这就是我如何一起使用整个东西:
using(var uow = new UnitOfWork(connectionstring))
{
using(var repository = new UserRepository(uio.Context))
{
//This is the place where a connection is opened in the database
var user = repository.GetUserByName(username);
}
}
//The connection is still open here even though
UnitOfWork 类实现 IDisposable 接口并在其 Dispose 方法中调用 Context.Dispose()。
当我关闭我的应用程序时,我的数据库中的打开连接消失了,所以我的问题是:这里发生了什么?:-) 我应该如何在我的 UnitOfWork 类中正确处理 Context (ObjectContext) 实例以关闭我的数据库中打开的连接?