简体   繁体   English

工作单元和存储库模式,并处理数据库上下文

[英]unit of work and repository pattern and dispose database context

I have unit of work class, I have there method to dispose database context. 我有工作单元类,我有处理数据库上下文的方法。 But I also pass database context to repository class - NotesRepository - should I also dispose context in NotesRepository class or it isn't necessary because this context was disposed in unit of work class? 但是我也将数据库上下文传递给存储库类-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);
    }
}

and this is repository class: 这是存储库类:

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);
    }        
}

I recommend doing this inside your UnitOfWork class 我建议在您的UnitOfWork类中执行此操作

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

Now it will be disposed approriately through the using - without needing to dispose it in the repository 现在,将通过使用将其适当地处置-无需将其处置在存储库中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM