Mid From PDF SOLID Design Patterns & 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
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details