0

我有工作单元类,我有处理数据库上下文的方法。但是我也将数据库上下文传递给存储库类 - 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);
    }        
}
4

1 回答 1

0

我建议在您的 UnitOfWork 类中执行此操作

using(var ctx = new DatabaseContext())
{
  var repo = new NotesRepo(ctx);
}

现在它将通过 using 适当地处理 - 而无需在存储库中处理它

于 2013-07-21T07:14:13.727 回答