Chuyển đến nội dung

Bài 38 · Testing and Patterns

The Repository and Unit of Work Debate

DbContext already is a repository and unit of work. Learn when a repository adds value, when it hurts, how to write query objects and handlers instead, with runnable stand-ins.

Open any older .NET tutorial and you will find IRepository<T>, GenericRepository<T> and IUnitOfWork wrapped around Entity Framework. Open a newer codebase and you will often find none of them, with services injecting DbContext directly. Both camps have reasons. This lesson explains the patterns, the argument, and a practical way to decide.

EF Core code is read-only on this site. The runnable blocks are stand-ins that model the patterns in plain C#.

What the patterns mean

  • A repository mediates between your domain and data mapping, offering a collection-like interface: Add, Remove, GetById, Find(...).
  • A unit of work tracks changes during a business operation and commits them together, or not at all.

Now look at what you already have (see DbContext and DbSet and SaveChanges and transactions):

Pattern EF Core equivalent
Repository per aggregate DbSet<T> (add, remove, find, query)
Unit of work DbContext with its change tracker; SaveChanges() commits in one transaction
Identity map The change tracker returns the same instance for the same key

So a generic wrapper such as the following mostly forwards calls:

C#
public interface IRepository<T> where T : class
{
    Task<T?> GetByIdAsync(int id);
    Task<List<T>> ListAsync();
    void Add(T entity);
    void Remove(T entity);
}

public class EfRepository<T>(AppDbContext db) : IRepository<T> where T : class
{
    public Task<T?> GetByIdAsync(int id) => db.Set<T>().FindAsync(id).AsTask();
    public Task<List<T>> ListAsync() => db.Set<T>().ToListAsync();
    public void Add(T entity) => db.Set<T>().Add(entity);
    public void Remove(T entity) => db.Set<T>().Remove(entity);
}

The case against a generic repository

  • It duplicates DbSet without adding behavior, so every EF feature needs a new method on the wrapper.
  • It leaks or limits. If ListAsync returns IQueryable, callers compose queries and the abstraction leaks the ORM. If it returns lists, you cannot Include, project, paginate or use AsNoTracking without adding a method for each need, and you end up with GetOrdersWithItemsAndCustomerAsync.
  • Fetching whole entities is wasteful. Reports and API responses usually want a projection (a few columns), which a generic repository cannot express (see query performance).
  • Fake-based tests give false confidence. A fake repository over a List<T> does not behave like SQL (see testing EF Core code).
  • Hiding the unit of work across several repositories forces an IUnitOfWork that only calls SaveChanges.

The case for abstractions

  • A named, intention-revealing API (orders.GetOverdueFor(customer)) documents business questions and hides the query.
  • One place per query avoids copy-paste differences. Duplicated Where conditions drift apart.
  • Swapping the data source (a cache, another service, an in-memory list for domain tests) works behind a small interface.
  • Domain-driven design: a repository per aggregate root (Order with its lines) enforces that you load and save aggregates as a whole and never reach into the middle.
  • Testing business logic without a database is easier against a small interface.

A middle path

Many teams settle on rules like these:

  1. Use DbContext directly in simple application services, query handlers and endpoints. It is already abstracted enough.
  2. When a query is used in more than one place or is complex, extract it into a named query class or extension method.
  3. For aggregate roots in a domain-rich model, add a specific repository (IOrderRepository) with the few methods the domain really needs, not a generic one.
  4. Let the application layer commit with SaveChanges once per use case, not inside the repository.
C# Stand-in: a specific repository with named queries

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

In production the EF Core version of GetOverdue would be db.Orders.Where(o => !o.Paid && o.PlacedOn < cutoff).AsNoTracking().ToListAsync(), behind the same interface.

Query objects, handlers and vertical slices

Instead of a repository per entity, you can organize code per use case: one small class per query or command, each using DbContext directly. This is the idea behind CQRS-style handlers and vertical slice architecture:

C#
public record GetOverdueOrders(int DaysAllowed);

public class GetOverdueOrdersHandler(AppDbContext db)
{
    public async Task<List<OverdueOrderDto>> HandleAsync(GetOverdueOrders query, CancellationToken ct)
    {
        var cutoff = DateTime.UtcNow.AddDays(-query.DaysAllowed);
        return await db.Orders
            .AsNoTracking()
            .Where(o => !o.Paid && o.PlacedOn < cutoff)
            .Select(o => new OverdueOrderDto(o.Id, o.Customer.Name, o.Total))
            .ToListAsync(ct);
    }
}

Each handler contains exactly the query it needs, including projections and includes, with no wasted abstraction. Tests for such handlers run against a real or SQLite database.

C# Stand-in: a handler per use case with a unit of work

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A quick decision guide

flowchart TD
    A["New data access code"] --> B{"Simple CRUD or one-off query?"}
    B -->|yes| C["Use DbContext directly"]
    B -->|no| D{"Reused in several places or complex?"}
    D -->|yes| E["Named query class or IQueryable extension"]
    D -->|no| C
    E --> F{"Rich domain with aggregates?"}
    F -->|yes| G["Specific repository per aggregate root"]
    F -->|no| E

Add structure when duplication or a real domain demands it, not before.

Common mistakes

  • Wrapping every entity in a generic repository on day one.
  • Returning IQueryable from a repository and calling it "abstraction".
  • Committing inside each repository method, which breaks atomic use cases.
  • Making repositories depend on each other.
  • Mocking DbSet and DbContext in tests instead of testing against a real database.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which EF Core types already play the roles of repository and unit of work?

    A DbSet behaves like a repository for an entity type, and the DbContext with SaveChanges is a unit of work.
  2. 2. What is a common problem with a generic IRepository<T>?

    Real queries need shaping; a generic wrapper either exposes IQueryable or accumulates ad hoc methods.
  3. 3. When is a specific repository per aggregate root most useful?

    In domain-driven designs a small, aggregate-focused repository keeps invariants intact.
  4. 4. Where should SaveChanges usually be called?

    Committing once per use case keeps the operation atomic.

Summary

  • DbSet is a repository and DbContext is a unit of work; wrapping them generically often adds ceremony without value.
  • Abstractions help when they give queries names, centralize reuse or protect aggregates.
  • Prefer named queries, handlers or specific repositories over a generic IRepository<T>.
  • Commit once per use case, and test data access against a real database.

Next: Project: a library lending system

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.