Design Patterns - Unit of Work Pattern in C# using Entity Framework Core

Before you look at the Unit of Work pattern example in C# using Entity Framework Core, you can see my post about what is the Unit of Work pattern.

Example of the Unit of Work interface in C#

public interface IUnitOfWork : IDisposable
{
  IUsersRepository UsersRepository { get; }

  Task<int> CommitChangesAsync();
}

About this code snippet:

Example of the implementation of the Unit of Work in C# using Entity Framework Core

public sealed class UnitOfWork : IUnitOfWork
{
  private ApplicationDbContext _context { get; }

  public IUsersRepository UsersRepository { get; }

  public UnitOfWork(ApplicationDbContext context)
  {
    this._context = context;

    this.UsersRepository = new UsersRepository(context);
  }

  public async Task<int> CommitChangesAsync()
  {
    return await this._context.SaveChangesAsync();
  }

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

About this code snippet:

  • It requires the application DbContext in its constructor arguments (Which is injected with dependency injection).
  • DbContext is already a Unit of Work provided by Entity Framework Core, so our repository will be just a thin layer to hide all the methods from DbContext and the implementation of our custom requirements.
  • It instance the implementations of the specialized repositories.