C# › Design Patterns in C#

How would you implement the Unit of Work pattern alongside the Repository pattern to coordinate multiple repository changes within a single transaction?

Advanced

Answer

Unit of Work tracks all changes made across multiple repositories during a business operation and commits them together in ONE atomic transaction (typically via SaveChanges() in EF Core) — this ensures related changes across different repositories either ALL succeed or ALL fail together, maintaining data consistency.
public interface IUnitOfWork : IDisposable {
  IRepository<Order> Orders { get; }
  IRepository<Customer> Customers { get; }
  Task<int> SaveChangesAsync();
}

// Usage
unitOfWork.Orders.Add(newOrder);
unitOfWork.Customers.Update(customer);
await unitOfWork.SaveChangesAsync(); // both changes committed together, atomically
Real-world example Ensuring an order placement (which updates both an Orders table AND a Customer's loyalty points) either fully succeeds or fully rolls back together.

Common follow-ups: Does Entity Framework Core's DbContext already implement the Unit of Work pattern internally, making a separate abstraction sometimes redundant?