SOLID & Design Patterns Interview Question #20

What is the Unit of Work Pattern?

SOLID Principles, Design Fundamentals, Repository, Factory, Strategy & Decorator Junior Beginner

Quick Interview Answer

The Unit of Work Pattern tracks a set of changes and coordinates their persistence as one logical transaction boundary. It allows multiple repository operations to be committed together.

Detailed Explanation

The Unit of Work Pattern tracks a set of changes and coordinates their persistence as one logical transaction boundary. It allows multiple repository operations to be committed together.

Entity Framework Core's DbContext already acts as a unit of work by tracking entity changes and persisting them through SaveChanges or SaveChangesAsync. A custom unit-of-work abstraction may still be useful when the application needs a specific boundary or multiple persistence collaborators.

Code Example

public interface IUnitOfWork
{
    Task<int> SaveChangesAsync(
        CancellationToken cancellationToken = default);
}

// EF Core DbContext already exposes:
await dbContext.SaveChangesAsync();