Tutorials ASP.NET Core MVC Mastery
Unit of Work
On this page
Unit of Work Pattern: Atomic Business Transactions
For any architect with 10+ years of experience, the Unit of Work (UoW) is not just a pattern—it is a core responsibility for data integrity.
The Problem: Distributed Transactions
If you have a UserRepo that saves the user, and an OrderRepo that saves the order, but your database crashes exactly between the two calls—what happens? You get Dirty Data (A user with no order, or vice versa).
The Solution: Unit of Work
Unit of Work ensures that multiple repositories share the same DbContext. It acts as a single gateway for the final SaveChangesAsync() call.
public class UnitOfWork : IUnitOfWork {
private readonly AppDbContext _db;
public IProductRepo Products { get; }
public IOrderRepo Orders { get; }
public async Task<int> SaveChangesAsync() => await _db.SaveChangesAsync();
}
Architect Insight: Persistence Ignorance
The goal of UoW is to maintain Persistence Ignorance. Your high-level business logic (the "What") should never care about the database implementation (the "How"). This is the pinnacle of clean architecture!