📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

In a Clean Architecture .NET solution, where do the Repository, Unit of Work and Specification abstractions live, and how do you use them without leaking EF Core into the Application and Domain layers? When would you skip them and use DbContext directly?

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.

Mid-Level Theory Intermediate architecture clean-architecture ef-core repository specification unit-of-work

🎯 Key points

  • Repository interfaces live in Domain (per aggregate) or Application; implementations in Infrastructure
  • One repository per aggregate root, not per table; methods named for use cases, returning aggregates
  • DbContext is already the unit of work; expose IUnitOfWork.SaveChangesAsync only if Application must not see DbContext
  • No IQueryable, DbSet, EF attributes or Include strings crossing into Application or Domain (a leak keeps the cost and loses the benefit)
  • Specifications as domain-named query objects evaluated in Infrastructure (Ardalis.Specification or expressions)
  • Reads bypass repositories: query services returning DTOs via AsNoTracking projections
  • Trade-off: abstractions buy persistence-ignorant, testable domain code at the cost of extra layers and less direct control of SQL; skip them for CRUD and vertical slices
  • Enforce with project references and architecture tests

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 IOrderRepository sits in the Domain project next to the Order aggregate, or in Application if I want the domain completely persistence-ignorant, and EfOrderRepository sits in Infrastructure. The repository is per aggregate root, not per table: Order and its OrderLines load and save together through one repository, with methods like GetAsync(OrderId, ct) and Add(order). No generic IRepository<T> with GetAll and Update; that just re-exposes the database.

For unit of work, EF Core's DbContext already tracks changes and commits them atomically in SaveChangesAsync. If my Application layer can't reference the DbContext, I add a one-method IUnitOfWork that the DbContext implements. Specifications are named queries like OverdueInvoicesFor(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 returning IQueryable from a repository: the moment Application calls .Include() or relies on EF translating a Where, 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 IQueryable everywhere. Abstractions should protect a rich domain, not decorate a CRUD app."


Where each piece lives

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

Use them or skip them

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

Production example

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.

🔍 What the interviewer is checking

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

  • Interfaces in the core, implementations in Infrastructure
  • One repository per aggregate; DbContext as the unit of work
  • Rejects IQueryable leaks; separates reads into query services
  • Knows when to skip repositories entirely
  • Mentions architecture tests to enforce the boundary

Red flags

  • Generic repository per table as the default
  • Custom unit of work wrapping transactions over DbContext
  • "Always use repositories for testability"

📚 Learn in depth

1. The dependency picture

+-------------------+        +---------------------+
| 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.

2. Why per aggregate

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.

3. Unit of Work

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.

4. Specifications without leaks

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.

5. Reads are different

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.

6. Signs the abstraction is leaking

  • Repository returns IQueryable<T> or takes Expression<Func<T,bool>>.
  • Application has using Microsoft.EntityFrameworkCore;.
  • Domain entities have [Column], [Key] or navigation properties only EF needs.
  • Tests mock repositories, then integration tests find translation errors.

Try it yourself

  1. Add an architecture test asserting Application and Domain don't reference Microsoft.EntityFrameworkCore.
  2. Convert a generic repository to an aggregate repository and count queries per request with LogTo before and after.
  3. Write an Ardalis.Specification spec in the Domain project and evaluate it in Infrastructure; check the generated SQL.
  4. Replace one query that loads aggregates for a list with a projection and measure memory with dotnet-counters.
  5. Write a Testcontainers integration test for a repository instead of mocking it.

💻 Code

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);
}

⚠ Common mistakes

  • Mistake: A generic 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.
  • Mistake: Returning 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.
  • Mistake: Wrapping 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.
  • Mistake: Repositories with different DbContext instances in one request. Why it is wrong: changes don't commit atomically. Instead: scoped DbContext shared by all repositories.
  • Mistake: Loading aggregates through repositories for list screens. Why it is wrong: over-fetching and N+1 queries. Instead: query services projecting to DTOs.
  • Mistake: Using specifications for read screens that load whole entities with several includes. Why it is wrong: specs that return tracked entities over-fetch compared with a 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.
  • Mistake: EF attributes on domain entities. Why it is wrong: couples the domain to persistence. Instead: IEntityTypeConfiguration<T> in Infrastructure.
  • Mistake: Adding repositories to a CRUD service "for testability". Why it is wrong: mocks hide translation errors; the layer protects no rules. Instead: DbContext directly with Testcontainers integration tests.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says they would sometimes skip repositories. Why: Checks the decision of whether to wrap DbContext at all.
    How to answer

    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.

    • Testability alone isn't a reason. Mocking repositories tests the mocks, and the EF in-memory provider ignores SQL semantics. I test persistence against SQL Server in Testcontainers either way.
    • Write side: repositories per aggregate root pay off when aggregates have invariants and must be loaded whole.
    • Read side: project straight from DbContext with Select and AsNoTracking. Never return IQueryable from a repository.
    • EF Core 10 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.

  2. When: Candidate mentions specifications or Ardalis.Specification. Why: Checks implementation detail of specifications with EF Core.
    How to answer

    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.

  3. When: Candidate refers to the dependency rule. Why: Checks overall understanding of Clean Architecture layers.
    How to answer

    Clean Architecture (Robert C. Martin, 2012) arranges code in concentric layers with one rule: source code dependencies point inwards.

    • Domain (centre): entities, value objects, domain events and business rules — no EF Core, no ASP.NET Core.
    • Application: use cases (commands, queries, handlers) plus the interfaces they need, such as IOrderRepository or IEmailSender.
    • Infrastructure: implements those interfaces with EF Core, Azure Service Bus, Blob Storage.
    • Presentation: endpoints and the composition root that wires implementations to interfaces.

    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.

🛠 Real-world problems: how you handle them

Generic repository leaking IQueryable causes N+1 queries
Situation
A [claims] platform in Clean Architecture used a generic `IRepository<T>` returning `IQueryable<T>`. Application handlers added `Include` and filters themselves. Claim detail pages served [~500] users.
Signals
Claim page load of [2.4 s]; EF Core logging showed [~200] queries per request; Application Insights dependency map showed SQL as [85%] of request time; unit tests with mocked repositories all passed.
Investigation
Enabled `LogTo` with query counts per request; profiled with Application Insights end-to-end transactions; grep for `Include` in the Application project; reviewed handlers that iterated navigation properties lazily.
Resolution
Introduced aggregate-specific repositories (`IClaimRepository.GetWithAssessmentsAsync`) that load the aggregate in one query with split queries where needed, and a query service projecting the claim page DTO. Removed `IQueryable` from the core.
Prevention
Architecture test banning `Microsoft.EntityFrameworkCore` in Application and Domain; Testcontainers integration tests asserting query counts for key pages; code review checklist item on repository return types.

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.

↩ Usually asked after

More in Architecture Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me