8

I've been looking at implementing these patterns in a project I am working on. The UoW has the database context and then instantiates a number of repositories with that context. My question is to do with disposing the context. A lot of articles I have seen have the repository as IDisposable and they then dispose of the context. This has confused me no end, am I missing something or (in my case) should it just be the UoW that disposes of the context? Also, should I be implementing IDisposable on my repositories?

Thanks

Chris

Neil Thompson
  • 6,356
  • 2
  • 30
  • 53
Chris
  • 318
  • 2
  • 5
  • 17

1 Answers1

12

Yes, the Unit of Work should implement IDisposable and dispose the context, not the repositories.

Here's one example:

public interface IUnitOfWork : IDisposable
{
    void Commit();
}

public class EntityFrameworkUnitOfWork<TContext> : IUnitOfWork 
    where TContext : DbContext, new()
{
    public EntityFrameworkUnitOfWork()
    {
        this.DbContext = new TContext();
        ConfigureContext(this.DbContext);
    }

    protected virtual void ConfigureContext(TContext dbContext)
    {
        dbContext.Configuration.ProxyCreationEnabled = false;
        dbContext.Configuration.LazyLoadingEnabled = false;
        dbContext.Configuration.ValidateOnSaveEnabled = false;
    }

    protected TContext DbContext { get; private set; }

    public void Commit()
    {
        this.DbContext.SaveChanges();           
    }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposing)
        {
            return;
        }

        if (this.DbContext == null)
        {
            return;
        }

        this.DbContext.Dispose();
        this.DbContext = null;
    }
}
devdigital
  • 34,151
  • 9
  • 98
  • 120
  • Only if you create the repository, like what is done here, you can dispose of it; otherwise the creator should call the dispose method. – Kamran May 03 '22 at 08:24