Mid SOLID

How do you implement Unit of Work in a .NET application?

In a .NET application (especially using Entity Framework), the Unit of Work is typically

implemented around the DbContext, as it already tracks changes and handles

transactions. Here's a simplified example:

// IUnitOfWork.cs

public interface IUnitOfWork : IDisposable

IProductRepository Products { get; }

ICustomerRepository Customers { get; }

int Complete();

// UnitOfWork.cs

public class UnitOfWork : IUnitOfWork

private readonly AppDbContext _context;

public IProductRepository Products { get; private set; }

public ICustomerRepository Customers { get; private set; }

public UnitOfWork(AppDbContext context)

_context = context;

Products = new ProductRepository(_context);

Customers = new CustomerRepository(_context);

public int Complete()

return _context.SaveChanges(); // All changes in one

transaction

public void Dispose()

_context.Dispose();

Then register it using Dependency Injection in Startup.cs or Program.cs:

services.AddScoped<IUnitOfWork, UnitOfWork>();

More from Design Patterns in C#

All questions for this course