【发布时间】:2014-05-21 00:55:14
【问题描述】:
根据这篇文章:http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application 我真的应该处理上下文吗?
例如我有一个带有 dispose 方法的控制器:
public class BlogController : Controller
{
private readonly INotesService _notesService;
public BlogController(INotesService notesService)
{
_notesService = notesService;
}
protected override void Dispose(bool disposing)
{
_notesService.Dispose();
base.Dispose(disposing);
}
}
所以我的控制器从服务调用 dispose 方法:
public class NotesService : INotesService
{
private readonly IUnitOfWork _unitOfWork;
public NotesService(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public void Dispose()
{
_unitOfWork.Dispose();
}
}
以及从工作单元调用dispose方法:
public class UnitOfWork : IUnitOfWork
{
private DatabaseContext context = new DatabaseContext();
private INotesRepository notesRepository;
public INotesRepository NotesRepository
{
get
{
if (this.notesRepository == null)
{
this.notesRepository = new NotesRepository(context);
}
return notesRepository;
}
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
this.context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
在每个控制器中我必须记得调用 Dispose 方法。更重要的是,如果我的控制器使用许多服务,我必须记住在也称为 Dispose 的控制器方法中对每个服务调用 Dispose 方法。
那么我真的应该处理数据库上下文吗?也许没必要。
【问题讨论】:
标签: asp.net asp.net-mvc