我有工作单元类,我有配置数据库上下文的方法。但是我也将数据库上下文传递给了存储库类 - NotesRepository - 我是否也应该在NotesRepository类中处理上下文,或者它是不必要的,因为这个上下文是以工作类为单位的?
public class UnitOfWork : IDisposable
{
private DatabaseContext context = new DatabaseContext();
private NotesRepository notesRepository;
public NotesRepository 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)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
这是存储库类:
public class NotesRepository
{
private DatabaseContext context;
public NotesRepository(DatabaseContext context)
{
this.context = context;
}
public IQueryable<Notes> GetAllNotes()
{
return (from x in context.Notes
orderby x.CreateDate descending
select x);
}
}
答案 0 :(得分:0)
我建议在UnitOfWork类中执行此操作
using(var ctx = new DatabaseContext())
{
var repo = new NotesRepo(ctx);
}
现在它将通过使用方式适当地处理 - 无需将其部署在存储库中