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.
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).
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();
}
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!