【发布时间】:2015-04-11 04:20:23
【问题描述】:
基类:
public abstract class Repository : IDisposable
{
private bool _disposed;
private DbContext _context;
public Repository(DbContext context)
{
_context = context;
}
public void SetSomething()
{
//...Access the database and set something for tracing
_context.Database.SqlQuery(....);
}
public void UnSetSomething()
{
//...Access the database and cancel something for tracing
_context.Database.SqlQuery(....);
}
#region Object Disposal
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~Repository()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
// free other managed objects that implement IDisposable only
if (_context != null)
{
_context.Dispose();
_context = null;
}
}
_disposed = true;
}
#endregion
}
子类:
public class ScheduleRepository : Repository
{
private AppContext _context;
public ScheduleRepository(DbContext context)
: base(context)
{
_context = (AppContext)context;
}
#region Object Disposal
bool _disposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~ScheduleRepository()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
// free other managed objects that implement IDisposable only
if (_context != null)
{
_context.Dispose();
_context = null;
}
}
_disposed = true;
base.Dispose(disposing);
}
#endregion
}
逻辑类:
public class ScheduleFacade
{
private ScheduleRepository _repository;
public ScheduleFacade()
{
_repository = new ScheduleRepository(AppContext.Create());
}
public ScheduleSetting GetScheduleById(string scheduleId)
{
if (!string.IsNullOrEmpty(scheduleId))
{
_repository.SetSomething();
ScheduleSetting settings = _repository.GetScheduleById(scheduleId);
_repository.UnSetSomething();
return LoadScheduleSettings(settings);
}
else
{
throw new ArgumentException("The scheduleId parameter cannot be empty.");
}
}
private ScheduleSetting LoadScheduleSettings(ScheduleSetting settings)
{
//...code ....
}
}
这是在抽象类实现上实现IDisposable 的正确方法吗?这没有像应有的那样遵循 DRY 原则,但我不清楚如何正确地做到这一点。
我想确保我正在适当地清理我的DbContext。
编辑:似乎需要更多信息来阐明我在做什么以及为什么我在构造函数中传递 DbContext(我在上面添加了更多代码以供重新阅读)。我需要抽象类中的 DbContext 来访问数据库并做一些工作。这不是我如何使用在多个子类之间共享的抽象类,从而使我能够遵守 DRY 原则并集中未来的维护吗?
如果我不通过构造函数将 DbContext 传递给抽象类(我想到了方法注入,但这将要求未来存储库的开发人员可能忘记将上下文传递给基类),我将如何将它传递给抽象类。
【问题讨论】:
-
为什么不让
context受保护,而不是在基类中有一个不同的 字段?然后你不需要重写任何基类的 dispose 函数。事实上,您现在没有覆盖它们,而是隐藏它们。 -
我不会在您的存储库中实现
IDisposable,因为您要处理的唯一内容 (context) 不是由您的存储库创建的,而是提供给它的。并非所有的类都符合这一点,但是让创建一次性物品的东西成为处置它的物品是一种很好的做法。 -
补充 Matthew 的正确观点,存储库应该不持有对上下文的引用 - 而它应该为每个请求创建一个上下文,所以没有必要让你的存储库一次性。
-
@Matthew 我更新了我的问题。请重新阅读。
-
首先尝试使用泛型,公共抽象类 Repository
: IDisposable where T : DbContext
标签: c# entity-framework entity-framework-6