我正在使用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)实例以关闭数据库中打开的连接?
答案 0 :(得分:1)
我认为你在处理Context方面做得很好。 Sql Server Provider支持连接池,因此您在using(var uow = new UnitOfWork(connectionstring))
块结束后看到的是池中的连接。
有关连接池的详细信息,请参阅此文章:http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx