【问题标题】:How to properly dispose the ObjectContext in a Repository and Unit of Work pattern如何在存储库和工作单元模式中正确处理 ObjectContext
【发布时间】:2011-09-29 00:31:12
【问题描述】:

我正在使用 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) 实例以关闭我的数据库中打开的连接?

【问题讨论】:

    标签: entity-framework-4 database-connection dispose objectcontext


    【解决方案1】:

    我认为您在处理上下文方面做得很好。 Sql Server Provider 支持连接池,因此您在using(var uow = new UnitOfWork(connectionstring)) 块结束后看到的是池中的连接。

    有关连接池的更多信息,请参阅这篇文章:http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx

    【讨论】:

      猜你喜欢
      • 2012-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-25
      • 2014-12-27
      相关资源
      最近更新 更多