Architecture-level placement of Repository, Unit of Work and Specification in Clean Architecture: interfaces in Domain or Application, implementations in Infrastructure, one repository per aggregate, DbContext as the unit of work, avoiding IQueryable and EF types in the core, and when using DbContext directly is the better choice.
In Clean Architecture the interfaces live in the core and the implementations in Infrastructure. I define one repository per aggregate root (IOrderRepository with GetAsync(OrderId) and Add), usually in the Domain or Application project, and implement it with EF Core in Infrastructure. DbContext already is the unit of work, so at most I expose a thin IUnitOfWork.SaveChangesAsync. Specifications are named query objects whose evaluation stays in Infrastructure.
The rule: no IQueryable, DbSet, Include or EF attributes cross into the core. Reads can skip repositories and project straight to DTOs. For CRUD or vertical slices, I'd skip the abstractions and use DbContext directly. The trade-off: isolation and testability of the domain versus extra layers.
"The Clean Architecture rule is that dependencies point inwards, so anything the domain or the use cases need from persistence is expressed as an interface in the core and implemented outside it. For repositories, that means
IOrderRepositorysits in the Domain project next to theOrderaggregate, or in Application if I want the domain completely persistence-ignorant, andEfOrderRepositorysits in Infrastructure. The repository is per aggregate root, not per table:Orderand itsOrderLinesload and save together through one repository, with methods likeGetAsync(OrderId, ct)andAdd(order). No genericIRepository<T>withGetAllandUpdate; that just re-exposes the database.For unit of work, EF Core's
DbContextalready tracks changes and commits them atomically inSaveChangesAsync. If my Application layer can't reference the DbContext, I add a one-methodIUnitOfWorkthat the DbContext implements. Specifications are named queries likeOverdueInvoicesFor(customerId): the core defines them in domain language, and Infrastructure translates them, often with Ardalis.Specification, into EF Core expressions. The leak I watch for is returningIQueryablefrom a repository: the moment Application calls.Include()or relies on EF translating aWhere, the abstraction is gone but you still pay for it.On the read side, I don't route queries through aggregate repositories. A query handler uses a read-only context or a query service that projects straight to DTOs with
AsNoTracking. And for a CRUD module or a vertical-slice service, I skip repositories entirely and use DbContext in the handler, tested with Testcontainers.The mistake I see is repositories added to every project by template, then bypassed or leaking
IQueryableeverywhere. Abstractions should protect a rich domain, not decorate a CRUD app."
| Piece | Project | Notes |
|---|---|---|
Order aggregate, value objects |
Domain | No EF attributes; configured with Fluent API in Infrastructure |
IOrderRepository |
Domain (or Application) | Per aggregate, use-case methods |
IUnitOfWork (optional) |
Application | Task<int> SaveChangesAsync(CancellationToken) |
Specifications (OverdueInvoicesSpec) |
Domain or Application | Expressed in domain terms |
EfOrderRepository, spec evaluator |
Infrastructure | Uses DbContext, Include, AsSplitQuery |
IEntityTypeConfiguration<Order> |
Infrastructure | Mapping kept out of the domain |
| Query handlers / read services | Application (interface) + Infrastructure | Project to DTOs, no tracking |
| Situation | Recommendation |
|---|---|
| Rich domain with aggregates and invariants | Repository per aggregate, DbContext as UoW |
| CRUD module, simple rules | DbContext directly in handlers |
| Vertical slice architecture | DbContext directly; maybe shared query helpers |
| Need to swap storage (rare) | Repository genuinely earns its place |
| Reporting and lists | Query services with projections, no repositories |
In a [claims] system with 12 aggregates, replacing a generic repository that returned IQueryable with aggregate-specific repositories removed 30+ Include calls from Application code and fixed an N+1 that was issuing 200 queries per claim page; page load dropped from 2.4 s to 180 ms.
Checks that the candidate can place persistence abstractions correctly in Clean Architecture, avoid leaking EF Core, and judge when the abstractions are worth it.
Green flags
IQueryable leaks; separates reads into query servicesRed flags
+-------------------+ +---------------------+
| Presentation (API)|------->| Application |
+-------------------+ | handlers, IUnitOfWork,
| | query service ports |
| +----------+----------+
| |
| v
| +---------------------+
| | Domain |
| | Order, IOrderRepository,
| | specifications |
| +----------^----------+
v |
+---------------------------------------+---------+
| Infrastructure: OrderingDbContext : IUnitOfWork |
| EfOrderRepository : IOrderRepository |
| SpecificationEvaluator, entity configurations |
+--------------------------------------------------+
Infrastructure references Domain and Application; the core references nothing in Infrastructure. The composition root (API Program.cs) wires them.
An aggregate is the unit of consistency. A repository that loads and saves whole aggregates guarantees invariants are checked on a complete object. Table-level repositories let code load an OrderLine without its Order and break invariants.
EF Core's change tracker records changes across all repositories sharing the same scoped DbContext, and SaveChangesAsync commits them in one transaction. All repositories in a request must share that instance (scoped lifetime). An explicit IUnitOfWork adds no behaviour; it only hides the DbContext type from Application.
A specification describes criteria, includes and ordering. With Ardalis.Specification, the spec class lives in the core and inherits from Specification<T>; the evaluator that turns it into EF Core calls lives in Infrastructure. The package has no EF dependency in its core assembly; only Ardalis.Specification.EntityFrameworkCore references EF. Specs can still leak if they encode EF-specific behaviour (split queries, raw SQL), so keep them to criteria, includes of the aggregate's own parts, and paging.
Command: handler -> IOrderRepository.GetAsync -> aggregate -> behaviour -> SaveChanges
Query: handler -> IOrderQueries.GetSummaryAsync -> AsNoTracking().Select(dto)
Loading full aggregates to show a list wastes memory and queries. Query services return DTOs shaped for the screen.
IQueryable<T> or takes Expression<Func<T,bool>>.using Microsoft.EntityFrameworkCore;.[Column], [Key] or navigation properties only EF needs.Microsoft.EntityFrameworkCore.LogTo before and after.Interfaces in the core, EF Core implementations in Infrastructure, and an architecture test guarding the boundary.
// Domain project: no EF Core reference.
namespace Ordering.Domain.Orders;
public interface IOrderRepository
{
Task<Order?> GetAsync(OrderId id, CancellationToken ct);
Task<IReadOnlyList<Order>> ListAsync(ISpecification<Order> spec, CancellationToken ct);
void Add(Order order);
}
public interface ISpecification<T>; // marker; criteria defined by concrete specs
public sealed record OverdueOrdersFor(CustomerId CustomerId, DateOnly Today) : ISpecification<Order>;
// Application project
namespace Ordering.Application;
public interface IUnitOfWork
{
Task<int> SaveChangesAsync(CancellationToken ct);
}
public sealed class CancelOrderHandler(IOrderRepository orders, IUnitOfWork uow)
{
public async Task HandleAsync(Guid orderId, CancellationToken ct)
{
var order = await orders.GetAsync(new OrderId(orderId), ct)
?? throw new KeyNotFoundException($"Order {orderId} not found.");
order.Cancel(); // invariant checked inside the aggregate
await uow.SaveChangesAsync(ct); // DbContext commits all tracked changes
}
}
// Infrastructure project: the only place that knows EF Core.
namespace Ordering.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Ordering.Application;
using Ordering.Domain.Orders;
public sealed class OrderingDbContext(DbContextOptions<OrderingDbContext> options) : DbContext(options), IUnitOfWork
{
public DbSet<Order> Orders => Set<Order>();
protected override void OnModelCreating(ModelBuilder b) => b.ApplyConfigurationsFromAssembly(typeof(OrderingDbContext).Assembly);
}
public sealed class EfOrderRepository(OrderingDbContext db) : IOrderRepository
{
public Task<Order?> GetAsync(OrderId id, CancellationToken ct) =>
db.Orders.Include(o => o.Lines).SingleOrDefaultAsync(o => o.Id == id, ct); // aggregate loaded whole
public async Task<IReadOnlyList<Order>> ListAsync(ISpecification<Order> spec, CancellationToken ct) => spec switch
{
OverdueOrdersFor s => await db.Orders.Include(o => o.Lines)
.Where(o => o.CustomerId == s.CustomerId && o.DueDate < s.Today && !o.IsPaid)
.ToListAsync(ct),
_ => throw new NotSupportedException(spec.GetType().Name)
};
public void Add(Order order) => db.Orders.Add(order);
}
// Architecture test (NetArchTest.Rules)
[Fact]
public void Core_does_not_depend_on_EF_Core()
{
var result = Types.InAssemblies([typeof(Order).Assembly, typeof(CancelOrderHandler).Assembly])
.ShouldNot().HaveDependencyOn("Microsoft.EntityFrameworkCore")
.GetResult();
Assert.True(result.IsSuccessful);
}
IRepository<T> for every table. Why it is wrong: it re-exposes the database, breaks aggregate boundaries and adds nothing over DbSet<T>. Instead: one repository per aggregate root with use-case methods.IQueryable<T> from repositories. Why it is wrong: this is an abstraction leak: Application now depends on EF Core's translation rules and Include semantics, so you can't change persistence without touching use cases, and unit tests over in-memory lists pass while the real SQL fails or runs N+1. You keep the cost of the layer and lose its benefit. Instead: return materialised aggregates or use specifications evaluated in Infrastructure.DbContext in a custom unit of work with its own transaction logic. Why it is wrong: duplicates the change tracker and causes nested-transaction bugs. Instead: DbContext is the unit of work; expose SaveChangesAsync at most.DbContext instances in one request. Why it is wrong: changes don't commit atomically. Instead: scoped DbContext shared by all repositories.Select projection, and composing many includes can cause cartesian explosion. Instead: use specs for command-side aggregate loading; use projections (or Ardalis' Select support with AsNoTracking) for reads, and check the generated SQL.IEntityTypeConfiguration<T> in Infrastructure.The question I ask is what the abstraction protects. In a rich domain, an aggregate repository protects invariants by ensuring whole aggregates are loaded and saved, and keeps the domain free of persistence concerns. In a CRUD module, it protects nothing and costs a layer, so I skip it. Both can coexist in one solution: the policy module uses repositories, the reference-data module uses DbContext directly.
I also separate reads from writes. Most of the pain people attribute to repositories comes from forcing queries through them. Repositories for commands, query services for reads, is the setup that ages best.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Aggregate repository + DbContext as UoW | Rich domain, invariants | One interface per aggregate | CRUD |
| Specifications (Ardalis) | Many reusable, named queries over aggregates | Library, learning | A handful of queries |
| DbContext directly | CRUD, vertical slices | Core depends on EF | Domain must be persistence-ignorant |
| Query services with projections | All read screens | Separate read code | Never a bad idea |
I'd measure queries per request and over-fetching (rows loaded vs displayed) with EF Core logging and Application Insights.
I decide by what the abstraction protects, not by habit. DbContext is already a repository and unit of work, so a wrapper has to earn its place.
DbContext with Select and AsNoTracking. Never return IQueryable from a repository.ExecuteUpdateAsync/ExecuteDeleteAsync bypass the change tracker and run at once, so they belong behind an intention-revealing method and need an explicit transaction to be atomic with SaveChanges.My answer flips for pure CRUD (skip repositories) or for Dapper, stored procedures or a second store (repositories hide them). The trade-off is domain protection against a layer that only renames EF Core.
A specification wraps one business rule ("in stock", "price below X") in an object that exposes it as an Expression<Func<T,bool>>. Because it's an expression tree, EF Core translates it to SQL; compile it once and the same rule also works in memory (IsSatisfiedBy).
Rules compose with And/Or/Not, built from Expression.AndAlso/OrElse/Not plus an ExpressionVisitor that replaces parameters so both sides share one lambda parameter.
That replaces a repository with dozens of GetProductsByXAndY methods with one ListAsync(spec) and small, named, testable rules. Ardalis.Specification packages this with ordering, includes and paging.
The trap: a spec typed as Func<T,bool> binds to Enumerable.Where, so EF loads the whole table and filters in memory. The trade-off is reusable rules against another abstraction to learn.
Clean Architecture (Robert C. Martin, 2012) arranges code in concentric layers with one rule: source code dependencies point inwards.
IOrderRepository or IEmailSender.The key move is dependency inversion: the database depends on the domain, not the other way round. The trade-off: testable, technology-independent rules in exchange for more projects, interfaces and mapping — overkill for simple CRUD.
How to tell it (STAR)
**S:** At [company], claim pages took [2.4 s] because a generic repository leaked `IQueryable` and handlers triggered [~200] queries per page. **T:** I [was asked to fix performance] without a rewrite. **A:** I measured queries per request with EF Core logging, replaced the generic repository with aggregate repositories for the [three] busiest aggregates, and added a projection-based query service for the page. I added an architecture test so EF Core couldn't creep back into Application. **R:** Page load fell to [180 ms] and queries per page to [3], and the pattern was adopted for the remaining aggregates over [two] sprints.
Last updated 23 Nov 2026.