我被告知需要处理我Entity Framework仓储类的实例,于是我创建了一个基类来强制进行这个实现。
我需要向专家确认:通过基类实现IDisposable
是否可行?
请注意,仓储类没有类成员变量。
/// Sample repository. Note that I return List<T> as IEnumerable,
/// and I use IDisposable
///
public class CompanyRepository : DisposableBase, ICompanyRepository
{
public IEnumerable<CompanyDetail> GetOneCompany(int? CompanyID)
{
var t = from c in _entities.CompanyDetail
where c.CompanyID == CompanyID.Value
select c;
return t.ToList();
}
}
/// <summary>
/// Disposable implementation based on advice from this link:
/// from Http://www.asp.net/entity-framework/tutorials/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
/// </summary>
public class DisposableBase : IDisposable
{
protected TLSAdminEntities1 _entities;
public DisposableBase()
{
_entities = new TLSAdminEntities1();
disposed = false;
}
private bool disposed ;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_entities.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
IDisposable
。派生类通常应通过覆盖Dispose(bool)
来添加其清理代码,而不是添加新的IDisposable.Dispose()
实现。 - supercat