Skip to main content

Lesson 2 of 8

Unit of Work Pattern

The Unit of Work coordinates multiple repository operations in a single transaction - a service calls multiple repositories and calls SaveChanges ONCE. This ensures all changes are committed or rolled back together.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

IUnitOfWork Implementation

IUnitOfWork Implementation
// Domain/Interfaces/IUnitOfWork.cs
public interface IUnitOfWork : IDisposable
{
    IProductRepository Products { get; }
    IOrderRepository Orders { get; }
    ICategoryRepository Categories { get; }

    Task<int> SaveChangesAsync(CancellationToken ct = default);
    Task BeginTransactionAsync(CancellationToken ct = default);
    Task CommitAsync(CancellationToken ct = default);
    Task RollbackAsync(CancellationToken ct = default);
}

// Infrastructure/Persistence/UnitOfWork.cs
public class UnitOfWork(
    AppDbContext db,
    IProductRepository products,
    IOrderRepository orders,
    ICategoryRepository categories) : IUnitOfWork
{
    private Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction? _transaction;

    public IProductRepository Products { get; } = products;
    public IOrderRepository Orders { get; } = orders;
    public ICategoryRepository Categories { get; } = categories;

    public Task<int> SaveChangesAsync(CancellationToken ct = default) =>
        db.SaveChangesAsync(ct);

    public async Task BeginTransactionAsync(CancellationToken ct = default) =>
        _transaction = await db.Database.BeginTransactionAsync(ct);

    public async Task CommitAsync(CancellationToken ct = default)
    {
        await SaveChangesAsync(ct);
        if (_transaction is not null) await _transaction.CommitAsync(ct);
    }

    public async Task RollbackAsync(CancellationToken ct = default)
    {
        if (_transaction is not null) await _transaction.RollbackAsync(ct);
    }

    public void Dispose() => _transaction?.Dispose();
}

// Registration:
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddScoped<ICategoryRepository, CategoryRepository>();

// Service using Unit of Work:
public class OrderService(IUnitOfWork uow)
{
    public async Task<Order> PlaceOrderAsync(PlaceOrderCommand cmd, CancellationToken ct)
    {
        await uow.BeginTransactionAsync(ct);
        try
        {
            // Multiple repositories, ONE SaveChanges
            var order = new Order { Id = Guid.NewGuid(), CustomerId = cmd.CustomerId, Status = "Placed", Total = 0, Items = [] };
            uow.Orders.Add(order);
            await uow.CommitAsync(ct); // saves ALL changes atomically
            return order;
        }
        catch
        {
            await uow.RollbackAsync(ct);
            throw;
        }
    }
}

interface IOrderRepository : IRepository<Order> { }
interface ICategoryRepository : IRepository<Category> { }
record PlaceOrderCommand(Guid CustomerId);

Tip

Tip

Practice Unit of Work Pattern in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Unit of Work Pattern from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Unit of Work Pattern is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done