Start With No Repository
For a small or medium service, inject DbContext into your application services and query it directly. It's already a unit of work, and each DbSet is already a repository. Add a layer when domain code starts having to know about persistence.
Every .NET codebase reaches a point where someone wraps DbContext in a generic IRepository<T>. The intent is honourable — abstract the persistence layer for “testability” and “swap-ability”. The result is usually less testable, never swapped, and silently slower. Six months later, a new developer asks why a list endpoint pulls back the whole table and computes the projection in memory. The answer: the repository returned IEnumerable<T> and execution materialised at the boundary.
IRepository<T> exposes IQueryable<T>, you haven't abstracted EF Core — you've coupled to it through a longer pipe. If it exposes IEnumerable<T>, every filter and projection runs client-side. Either way, the pattern is paying negative dividends.The Repository pattern (Fowler, PoEAA, 2002) mediates between the domain and the data-mapping layer. EF Core's DbContext is already a Unit of Work, and each DbSet<T> is already an in-memory collection façade backed by storage. Adding a layer on top has to earn its existence. Below is when it does, and what I use when it doesn't.
What Repository Really Solves
Strip the pattern back to its purpose: keep domain code free of persistence concerns. That is a real problem worth solving — but only when the domain code has persistence concerns leaking in. A controller that calls db.Orders.Where(...) doesn't have leakage; a domain service that has to know about SaveChangesAsync ordering does.
flowchart TB
subgraph Anti["Anti-pattern: Generic Repository"]
A1[IRepository<T>.GetAll]
A2[IRepository<T>.Find]
A3[IRepository<T>.Add/Update/Delete]
A1 --> A4[Service does projection client-side]
A2 --> A4
end
subgraph Useful["Useful: Domain Repository"]
B1[IOrderRepository.FindOpenOrdersForCustomer]
B2[IOrderRepository.SaveAsync]
B1 --> B3[Hand-written EF query, intent-revealing]
B2 --> B4[Wraps SaveChanges + outbox]
end
subgraph Spec["Useful: Specification"]
C1[Specification<Order>.Where]
C2["OrderRepo.Query<TResult>(spec, projector)"]
C1 --> C2
endThe three sane shapes:
- No repository. Inject
DbContextdirectly into application services. Default for small/medium services — the “you aren't gonna need it” option. - Domain repository. One interface per aggregate root (e.g.
IOrderRepository) with intent-revealing methods (FindWithLines,FindOpenOrdersForCustomer). NoIQueryableescapes. - Specification pattern. Encapsulate query criteria as objects so they can be unit-tested, composed, and reused. Pair with a thin repo that accepts a spec.
Check it: Open your repository interface and read the return types. IEnumerable means filtering in memory, and IQueryable means EF Core has leaked through.
Domain Repository + Specification
3.1 The domain repository
One interface per aggregate, named with the verbs your domain actually uses. The implementation lives in the infrastructure project and is the only place that touches DbContext.
// Domain layer — depends on nothing
public interface IOrderRepository
{
Task<Order?> FindAsync(OrderId id, CancellationToken ct);
Task<IReadOnlyList<Order>> FindOpenOrdersForCustomer(CustomerId customer, CancellationToken ct);
Task AddAsync(Order order, CancellationToken ct);
}
// Infrastructure layer — depends on EF Core
internal sealed class OrderRepository(AppDb db) : IOrderRepository
{
public Task<Order?> FindAsync(OrderId id, CancellationToken ct) =>
db.Orders
.Include(o => o.Lines)
.SingleOrDefaultAsync(o => o.Id == id, ct);
public async Task<IReadOnlyList<Order>> FindOpenOrdersForCustomer(CustomerId customer, CancellationToken ct) =>
await db.Orders
.Where(o => o.CustomerId == customer && o.Status == OrderStatus.Open)
.OrderByDescending(o => o.PlacedAt)
.ToListAsync(ct);
public async Task AddAsync(Order order, CancellationToken ct) =>
await db.Orders.AddAsync(order, ct);
}Notice what the repository does not have: SaveChangesAsync. That belongs to a Unit-of-Work boundary the application service controls — typically a single SaveChangesAsync call at the end of a use case, often paired with an outbox/inbox.
Check it: Read the method names on one repository. They should be verbs from your domain, and none should return IQueryable.
3.2 The specification pattern, when criteria proliferate
When a single aggregate has many filter combinations (search, paging, multi-tenant scoping, soft-delete, security trim), specifications keep the repo small.
public abstract class Specification<T>
{
public Expression<Func<T, bool>>? Criteria { get; protected init; }
public List<Expression<Func<T, object>>> Includes { get; } = [];
public int? Take { get; protected init; }
public int? Skip { get; protected init; }
}
public sealed class OpenOrdersForCustomer : Specification<Order>
{
public OpenOrdersForCustomer(CustomerId id, int page, int size)
{
Criteria = o => o.CustomerId == id && o.Status == OrderStatus.Open;
Skip = page * size; // paging needs a stable OrderBy, which this sketch leaves out
Take = size;
}
}
public interface IRepository<T> where T : class
{
Task<IReadOnlyList<TResult>> QueryAsync<TResult>(
Specification<T> spec,
Expression<Func<T, TResult>> projector,
CancellationToken ct);
}
internal sealed class EfRepository<T>(AppDb db) : IRepository<T> where T : class
{
public async Task<IReadOnlyList<TResult>> QueryAsync<TResult>(
Specification<T> spec,
Expression<Func<T, TResult>> projector,
CancellationToken ct)
{
IQueryable<T> q = db.Set<T>().AsNoTracking();
if (spec.Criteria is not null) q = q.Where(spec.Criteria);
foreach (var inc in spec.Includes) q = q.Include(inc);
if (spec.Skip is { } s) q = q.Skip(s);
if (spec.Take is { } t) q = q.Take(t);
return await q.Select(projector).ToListAsync(ct);
}
}Specifications are unit-testable in isolation (just compile the expression and run it against an in-memory list), composable through And/Or combinators, and the repo stays a one-method affair. Crucially, the projector is supplied per-call so every read path stays projection-native — no entity hydration unless the caller asks.
3.3 Unit-of-Work — usually unnecessary, sometimes essential
EF Core's DbContext already coordinates a transaction-scoped change set, so a hand-rolled IUnitOfWork typically reduces to a thin facade over SaveChangesAsync. It earns its place when the transaction must span multiple contexts, span an outbox publish, or remain controllable from a use-case orchestrator.
public interface IUnitOfWork { Task<int> CommitAsync(CancellationToken ct); }
internal sealed class EfUnitOfWork(AppDb db, IOutbox outbox) : IUnitOfWork
{
public async Task<int> CommitAsync(CancellationToken ct)
{
await using var tx = await db.Database.BeginTransactionAsync(ct);
var changes = await db.SaveChangesAsync(ct);
await outbox.FlushAsync(ct); // same transaction
await tx.CommitAsync(ct);
return changes;
}
}Check it: Make the second of two writes in one use case fail. The first should be rolled back with it.
Pitfalls That Quietly Kill Throughput
- Generic
IRepository<T>.GetAll. If it returnsIEnumerable<T>, every later.Whereruns client-side. If it returnsIQueryable<T>, you've leaked EF Core through your “abstraction”. Either way the pattern provides nothing but ceremony. - One repository per entity. Repositories belong to aggregate roots, not to every table. If
OrderLineonly has meaning inside anOrder, there is noIOrderLineRepository. - Mocking
IRepository<T>for unit tests. The cost is low only because the test is now decoupled from reality. EF Core's in-memory provider lies about transactions, concurrency, and SQL behavior. PreferTestcontainerswith the real database for repository tests; reserve mocks for layers above. - Hiding
SaveChangesAsyncinside the repo. Now multiple repository calls each commit independently and you lose atomicity. The use-case is the right transactional boundary; expose UoW or callSaveChangesAsyncin the application service. - Repository as DTO mapper. Returning DTOs from the repo couples the persistence layer to presentation needs. Project at the use-case layer where the contract lives.
- The fictional “swap to MongoDB” argument. Swapping a database is rarely just an interface change. The data model, query patterns, transactional guarantees and operational tooling all differ. Don't pay the abstraction cost for a refactor that will never happen.
Testing Without a Repository
The usual defence of a repository is testability: mock it, and you never touch a database. That test proves less than it seems to, because the query is exactly what you wanted to check. With Testcontainers you can run tests against real Postgres or SQL Server in seconds, so EF Core's translation, indexes and constraints all get exercised. I'd only mock at the boundary with something you don't own, such as a payment API. If you keep a repository for domain reasons, test it against the real engine. Avoid the in-memory provider, since it doesn't behave like a relational database and will pass code that fails in production.
A Rule for Deciding
Keep a repository when it protects a real domain rule, such as "an order is always loaded with its lines", or when you must hide a store that may genuinely change. Drop it when it only forwards calls to DbContext. A quick test: if most of your repository methods are one line long, the abstraction isn't doing any work. Coding agents copy whatever pattern they find, so an unnecessary layer tends to multiply. Deleting it from one feature and writing that down in your repo instructions stops the spread.
Check it: Count the repository methods that are one line long. If that's most of them, the abstraction isn't doing any work.
Try It on Your Own System This Week
Three checks on a service you already have, about an hour in total:
- Log the SQL for one list endpoint. It should have a WHERE clause, and only the columns you show.
- Count your repositories and your aggregate roots. A repository for every table is too many.
- Find a test that mocks a repository. Ask what it would catch if the query were wrong.
What I Would Do Instead
- Default to no repository. Inject
DbContextinto application services. Add a repository when domain code starts learning persistence concerns. - When you do add one, make it a domain repository per aggregate root with intent-revealing methods. Never expose
IQueryable. - Reach for specifications when filter combinations explode. Always pass a projector so reads stay column-trim.
- Keep
SaveChangesAsyncat the use-case boundary. Wrap in a Unit-of-Work only when you need to coordinate side-effects (outbox, multiple contexts). - Test repositories against the real database with
Testcontainers. Save mocking for the layers above. - The best repository is often the one you didn't write. Pattern adoption is a cost; require it to clear a real bar of value first.