工作单位,存储库和IDisposable

时间:2013-04-12 13:44:32

标签: entity-framework repository-pattern unit-of-work

我一直在寻找在我正在开发的项目中实现这些模式。 UoW具有数据库上下文,然后使用该上下文实例化许多存储库。我的问题是处理上下文。我见过很多文章都将存储库作为IDisposable,然后处理上下文。这让我感到困惑,我错过了什么,或者(在我的情况下)是否只是处理上下文的UoW?另外,我应该在我的存储库中实现IDisposable吗?

由于

克里斯

1 个答案:

答案 0 :(得分:11)

是的,工作单元应该实现IDisposable并处理上下文,而不是存储库。

以下是一个例子:

public interface IUnitOfWork : IDisposable
{
    void Commit();
}

public class EntityFrameworkUnitOfWork<TContext> : IUnitOfWork 
    where TContext : DbContext, new()
{
    public EntityFrameworkUnitOfWork()
    {
        this.DbContext = new TContext();
        ConfigureContext(this.DbContext);
    }

    protected virtual void ConfigureContext(TContext dbContext)
    {
        dbContext.Configuration.ProxyCreationEnabled = false;
        dbContext.Configuration.LazyLoadingEnabled = false;
        dbContext.Configuration.ValidateOnSaveEnabled = false;
    }

    protected TContext DbContext { get; private set; }

    public void Commit()
    {
        this.DbContext.SaveChanges();           
    }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposing)
        {
            return;
        }

        if (this.DbContext == null)
        {
            return;
        }

        this.DbContext.Dispose();
        this.DbContext = null;
    }
}
相关问题