Chr*_*ris 7 entity-framework unit-of-work repository-pattern
我一直在寻找在我正在开发的项目中实现这些模式.UoW具有数据库上下文,然后使用该上下文实例化许多存储库.我的问题是处理上下文.我见过很多文章都将存储库作为IDisposable,然后处理上下文.这让我感到困惑,我错过了什么,或者(在我的情况下)是否只是处理上下文的UoW?另外,我应该在我的存储库中实现IDisposable吗?
谢谢
克里斯
dev*_*tal 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;
}
}
Run Code Online (Sandbox Code Playgroud)