No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

1.5KB

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.

AppDbContext
  ├─ DbSet<Customer>
  ├─ DbSet<Order>
  └─ DbSet<Product>

IGenericRepository<TEntity>
GenericRepository<TEntity>

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.

Powered by TurnKey Linux.