Covers DDD repositories as collections of aggregates (one per root), domain services versus application services, and a worked funds-transfer example showing where each piece of logic lives.
A DDD repository gives collection-like access to whole aggregates: GetAsync(id), Add(order). There is one per aggregate root, not per table, so there is no OrderLineRepository. Its interface sits with the domain or application layer; the EF Core implementation sits in infrastructure.
A domain service holds domain logic that does not belong to a single aggregate, like a funds transfer that applies rules to two accounts, or a pricing policy. It is stateless and free of infrastructure. An application service (or command handler) orchestrates a use case: load aggregates, call the domain, save, publish events, manage the transaction. It contains no business rules. The trade-off: domain services are useful, but reach for them only after asking whether the logic belongs on an aggregate, or the model turns anaemic.
"In DDD a repository pretends to be an in-memory collection of aggregates. You ask it for an Order by id and you get the whole aggregate, lines and all, ready to enforce its rules; you add a new Order to it; and the unit of work saves it. That is why there is one repository per aggregate root: there's no OrderLine repository, because nobody outside the Order should load or save lines on their own. The interface lives next to the domain,
IOrderRepositorywith three or four methods, and the implementation in Infrastructure wraps EF Core. It doesn't exposeIQueryable, because then every caller can write queries that ignore the aggregate.Services come in two kinds and people mix them up. A domain service is part of the model: it holds a business rule that doesn't naturally belong to one entity. The classic example is a transfer between two accounts. Debiting one and crediting the other isn't the responsibility of either account alone, and there are rules about it: daily transfer limits, same currency, the source can't go below its overdraft. So a
FundsTransferService.Transfer(from, to, amount)in the domain applies those rules by callingfrom.Withdrawandto.Deposit. It's stateless and has no idea a database exists.The application service, or command handler, is the use case. It loads both accounts through the repository, calls the domain service, saves, and writes an integration event to the outbox. It owns the transaction and knows about the outside world, but it doesn't decide anything about money. The mistake I see is the opposite: every rule ends up in an
AccountServiceand the entities become property bags. My order of preference is: method on the aggregate first, domain service when the logic truly spans aggregates, and the application service only coordinates."
| Piece | Responsibility | Depends on | Example |
|---|---|---|---|
| Aggregate | Its own invariants | Nothing | Account.Withdraw(amount) |
| Domain service | Rules spanning aggregates or not owned by one | Domain types only | FundsTransferService.Transfer |
| Repository (interface) | Load and save whole aggregates | Domain types | IAccountRepository.GetAsync |
| Repository (implementation) | EF Core queries, Include | EF Core | EfAccountRepository |
| Application service / handler | Orchestrate use case, transaction, events | Repositories, domain, outbox | TransferFundsHandler |
| Question | Domain service | Application service |
|---|---|---|
| Would a domain expert recognise the logic? | Yes | No (it is plumbing) |
| Does it call a database, queue or HTTP? | Never | Yes, through abstractions |
| Is it named in the ubiquitous language? | TransferFunds, PricingPolicy |
TransferFundsHandler |
| Does it own the transaction? | No | Yes |
In a [savings product], transfer rules were duplicated in the mobile API, the internet-banking API and a scheduled-payments job, and two of them disagreed on the daily limit. Moving them into a FundsTransferService domain service called from three thin handlers removed the inconsistency and cut transfer-rule tests from [three suites to one] with [40] fast unit tests.
Checks that the candidate can place logic correctly between aggregates, domain services and application services, and understands what a DDD repository is for.
Green flags
Red flags
DbContextApplication layer Infrastructure
----------------- --------------
IAccountRepository ◄── implements ── EfAccountRepository
GetAsync(AccountId) db.Accounts.Include(a => a.Holds)
Add(Account) .SingleOrDefaultAsync(...)
Add, Get, Remove; saving happens through the unit of work (SaveChangesAsync) because EF Core tracks changes.A repository per table lets code load an OrderLine and change it without the Order knowing, breaking the order's total. It also tempts generic IRepository<T> with GetAll() and Update(T), which duplicates what DbSet<T> already does.
Signs that logic belongs in a domain service:
Transfer(from, to)).PremiumCalculator, ShippingCostPolicy).Domain services are stateless. They can depend on domain abstractions (IExchangeRateProvider defined in the domain) but not on EF Core or HTTP.
POST /transfers
│
▼
TransferFundsHandler (application)
├─ from = accounts.GetAsync(fromId)
├─ to = accounts.GetAsync(toId)
├─ result = transferService.Transfer(from, to, amount, today) (domain)
│ ├─ checks: same currency, daily limit
│ ├─ from.Withdraw(amount) ── checks overdraft
│ └─ to.Deposit(amount)
├─ outbox.Add(new FundsTransferred(...))
└─ SaveChangesAsync() (one transaction: two account rows + outbox)
This touches two aggregates in one transaction: a deliberate exception to the usual rule, justified because money must not be created or destroyed. In a high-scale system you would instead model a Transfer aggregate and use a saga.
In Clean Architecture the repository interfaces live in Application (or Domain); Infrastructure references both and implements them. DI wiring happens in the composition root (Program.cs).
TimeProvider.Funds transfer: aggregate methods, a domain service, a repository and a thin handler.
namespace Banking.Domain;
public readonly record struct AccountId(Guid Value);
public sealed record Money(decimal Amount, string Currency);
public sealed class Account
{
private Account() { }
public Account(AccountId id, string currency, decimal overdraftLimit)
=> (Id, Currency, OverdraftLimit) = (id, currency, overdraftLimit);
public AccountId Id { get; private set; }
public string Currency { get; private set; } = "AUD";
public decimal Balance { get; private set; }
public decimal OverdraftLimit { get; private set; }
public byte[] RowVersion { get; private set; } = [];
public bool CanWithdraw(Money m) => m.Currency == Currency && Balance - m.Amount >= -OverdraftLimit;
public void Withdraw(Money m)
{
if (!CanWithdraw(m)) throw new InvalidOperationException("Insufficient funds.");
Balance -= m.Amount;
}
public void Deposit(Money m)
{
if (m.Currency != Currency) throw new InvalidOperationException("Currency mismatch.");
Balance += m.Amount;
}
}
// Domain service: a rule that spans two aggregates. No infrastructure.
public sealed class FundsTransferService
{
public const decimal DailyLimit = 10_000m;
public string? Transfer(Account from, Account to, Money amount, decimal alreadyTransferredToday)
{
if (from.Id == to.Id) return "transfer.same_account";
if (from.Currency != to.Currency) return "transfer.currency_mismatch";
if (alreadyTransferredToday + amount.Amount > DailyLimit) return "transfer.daily_limit";
if (!from.CanWithdraw(amount)) return "transfer.insufficient_funds";
from.Withdraw(amount);
to.Deposit(amount);
return null; // success
}
}
// Repository: one per aggregate root, aggregate-shaped.
public interface IAccountRepository
{
Task<Account?> GetAsync(AccountId id, CancellationToken ct);
Task<decimal> TransferredTodayAsync(AccountId id, DateOnly day, CancellationToken ct);
Task SaveChangesAsync(CancellationToken ct);
}
namespace Banking.Application;
using Banking.Domain;
public sealed record TransferFunds(Guid From, Guid To, decimal Amount, string Currency);
// Application service: orchestration only; no business rules.
public sealed class TransferFundsHandler(IAccountRepository accounts, FundsTransferService transfers, TimeProvider clock)
{
public async Task<string?> HandleAsync(TransferFunds cmd, CancellationToken ct)
{
var from = await accounts.GetAsync(new AccountId(cmd.From), ct);
var to = await accounts.GetAsync(new AccountId(cmd.To), ct);
if (from is null || to is null) return "transfer.account_not_found";
var today = DateOnly.FromDateTime(clock.GetUtcNow().UtcDateTime);
var sent = await accounts.TransferredTodayAsync(from.Id, today, ct);
var error = transfers.Transfer(from, to, new Money(cmd.Amount, cmd.Currency), sent);
if (error is not null) return error;
await accounts.SaveChangesAsync(ct); // both rows in one transaction; rowversion protects each
return null;
}
}
// Program.cs: composition root.
builder.Services.AddScoped<IAccountRepository, EfAccountRepository>();
builder.Services.AddSingleton<FundsTransferService>(); // stateless
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddScoped<TransferFundsHandler>();
OrderLineRepository). Why it is wrong: children can be changed without the root checking invariants. Instead: one repository per aggregate root; changes to children go through the root.IRepository<T> with GetAll, Update and IQueryable. Why it is wrong: it duplicates DbSet<T>, leaks query logic everywhere and ignores aggregate boundaries. Instead: small, aggregate-specific interfaces.AsNoTracking().Select(...); load the aggregate when the screen actually runs a business operation or needs the rules (for example, showing which actions are allowed).SaveChanges inside each repository method. Why it is wrong: a use case touching two aggregates commits twice and can leave half the change. Instead: save once per use case in the handler (unit of work).Account, catch DbUpdateConcurrencyException in the handler and retry the use case or return 409.Transfer aggregate and use a saga (debit, credit, compensate on failure) with an outbox, accepting eventual consistency.Repositories in DDD are about protecting aggregate boundaries, not about hiding EF Core for its own sake. In a small service where the aggregates are simple, using DbContext directly in handlers is a legitimate choice; the boundary is then kept by convention and architecture tests. Domain services are a pressure valve: necessary sometimes, but a codebase full of them is usually an anaemic model in disguise.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Aggregate repository interface | Rich domain, several use cases per aggregate | One small interface + implementation per root | Simple CRUD modules |
DbContext in handlers |
Small service, simple aggregates, strong tests | Boundary kept by discipline | Many teams, complex invariants |
| Domain service | Logic spanning aggregates, named policies | Another type to find | Logic that fits one aggregate |
I watch the ratio of logic in services to logic in entities during review; when services keep growing, the model needs attention.
These are three layers of responsibility:
order.Submit()), and they come first.When everything goes into a fat OrderService, entities become property bags: the anaemic domain model. Controllers should only translate HTTP. The trade-off is richer models and clear boundaries against more types and more thought about where each rule lives.
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.
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.
How to tell it (STAR)
**S:** At [company], reconciliation found [about 40] transfers a week over the daily limit. **T:** I owned [finding the cause and making the rule consistent across channels]. **A:** I compared the three channel implementations, found the scheduled job used UTC days and ignored holds, shipped a hot-fix, then proposed one domain service for the rules. I wrote an ADR, built it with [a colleague] and switched channels one at a time behind tests. **R:** Limit breaches went to [zero] and the transfer rules now live in one place with [40] unit tests running in [under a second].
Last updated 23 Nov 2026.