# Unit of Work Pattern Notes Use the Unit of Work pattern when a C#/.NET application needs one clear transaction boundary across multiple repository operations. ## Core idea A Unit of Work owns or coordinates one EF Core `DbContext`. Repositories use that same context to stage changes. The application service or controller calls `SaveChangesAsync` once at the end of the logical operation. ## Recommended shape ```text AppDbContext ├─ DbSet ├─ DbSet └─ DbSet IGenericRepository GenericRepository IUnitOfWork ├─ Customers ├─ Orders ├─ Products └─ SaveChangesAsync() ``` ## Best practices - Register `DbContext`, repositories, and Unit of Work with compatible lifetimes, usually scoped in ASP.NET Core. - Keep one shared context per Unit of Work. - Let repositories stage changes; let Unit of Work commit changes. - Prefer async EF Core methods with cancellation tokens. - Use `AsNoTracking` for read-only queries. - Prefer typed `Include` expressions over string include paths. - Keep business rules in services/domain methods, not generic repositories. - Avoid mixing direct `DbContext` access and Unit of Work access in the same workflow. ## When not to use it Do not add a custom Unit of Work just for ceremony. EF Core `DbContext` already provides Unit of Work behavior. A custom abstraction is most useful when the project has a repository convention, a testing boundary, or complex operations spanning multiple repositories.