A code review of a cargo-cult Clean Architecture solution: anaemic entities, a broken dependency rule, table-shaped repositories, mapping chains and needless interfaces, ranked by severity with a rewrite and review close-out.
I'd rank findings by impact, not by how ugly they look:
Status = Shipped on an unpaid order. A repository per table splits one aggregate across several saves, risking partial writes.The rewrite: a rich aggregate, one repository per aggregate root with the port owned by Application, projection queries for reads, and interfaces only at real boundaries — enforced by an architecture test.
"I'd start by separating what produces wrong data from what is merely heavy. The most serious problem is the anaemic domain: entities with public setters and no behaviour mean the rules live in whichever handler touches the field, so nothing stops a handler setting an unpaid order to Shipped. Close behind is the repository per table:
OrderRepositoryandOrderLineRepositoryeach callSaveChanges, so adding a line and updating the total can half-succeed. Those two findings are blocking, because they can corrupt data.Next, the dependency rule. Application references Infrastructure, so handlers use the concrete
AppDbContextand the Stripe client directly. That's not Clean Architecture any more; it's layering with extra projects. Then there's waste: each request goes Request → Command → Entity → Dto → Response through AutoMapper profiles, which costs allocations and, worse, a renamed property silently maps to null. And every class has anIFoowith oneFoo, which doubles the files without creating a single real seam. For example, on [a policy admin system] I reviewed, [a renamed field was dropped by a mapping profile and went unnoticed for two weeks], which is what convinced the team to simplify.The mistake I see in reviews like this is leaving forty comments of equal weight. I'd mark the first two as blocking, propose the rewrite of one aggregate as a worked example, add an architecture test for the dependency rule, and capture the rest in an ADR so the team simplifies incrementally rather than in a big-bang refactor. The goal isn't purity; it's that the layers protect something."
// Domain/Order.cs
public class Order // 1 anaemic: public setters, no behaviour
{
public Guid Id { get; set; }
public string Status { get; set; } = "Draft";
public decimal Total { get; set; }
}
// Application/Orders/AddLineHandler.cs
using Infrastructure.Persistence; // 2 Application -> Infrastructure
public class AddLineHandler(
IOrderRepository orders, // 3 repository per table
IOrderLineRepository lines,
IMapper mapper, // 4 mapping chain
AppDbContext db) : IAddLineHandler // 5 one-implementation interface
{
public async Task<OrderDto> Handle(AddLineCommand cmd)
{
var order = await orders.GetAsync(cmd.OrderId);
var line = mapper.Map<OrderLine>(cmd);
await lines.AddAsync(line); // SaveChanges #1
order.Total += line.Price * line.Qty; // 6 rule in the handler; no status check
await orders.UpdateAsync(order); // SaveChanges #2 -> partial write possible
return mapper.Map<OrderDto>(order); // later mapped again to OrderResponse
}
}
| # | Severity | Finding | Why it matters |
|---|---|---|---|
| 1, 6 | Wrong data | Anaemic entity; invariant ("only draft orders change") not enforced; total updated by hand | Invalid states reachable from any handler |
| 3 | Wrong data | Repository per table, two SaveChanges calls |
Line saved, total not: inconsistent aggregate |
| 2 | Design (high) | Application references Infrastructure and AppDbContext |
Dependency rule broken; use cases tied to EF Core concretes |
| 4 | Bugs + perf | Four-hop mapping via AutoMapper | Silent nulls on rename; extra allocations per request |
| 5 | Ceremony | IAddLineHandler and similar one-implementation interfaces |
Indirection with no seam; slower navigation |
See the code example: an Order aggregate that owns its lines and total, an IOrderRepository port in Application for the aggregate root only, a handler that loads, calls one method and saves once, and a read query that projects straight to the response.
| Comment | Type |
|---|---|
Enforce invariants in Order; remove public setters |
Blocking |
One repository per aggregate root, single SaveChangesAsync |
Blocking |
| Remove Application → Infrastructure reference; add ArchUnitNET rule | Blocking for new code, baseline existing |
| Replace mapping chain with projection for reads, explicit mapping for writes | Suggested, incremental |
| Drop interfaces without a second implementation or test seam | Suggested |
I'd follow up with an ADR ("What each layer protects") and a short pairing session on one aggregate.
After a review like this on a 40-endpoint service, the team rewrote three aggregates over two sprints. Mapping profiles fell from 62 to 9, handler files shrank by about 35%, and a class of production bugs — orders edited after dispatch, about 15 a month — dropped to zero once the invariant moved into the aggregate.
Checks that the candidate can review an architecture critically, rank issues by real impact and propose an incremental, convincing rewrite.
Green flags
Red flags
Architecture reviews tempt you to lead with structure. But users feel wrong data first. Rank:
crash / data corruption / security > wrong results > diagnostics & perf > design & ceremony
The anaemic model and table repositories are in the first bucket because they allow invalid states and partial writes.
Table-shaped: Aggregate-shaped:
[OrderRepository] -> Orders [OrderRepository] -> Order (root)
[OrderLineRepository] -> Lines +-- Lines (owned)
two SaveChanges +-- Total (derived)
one SaveChanges = one transaction
An aggregate is a consistency boundary: everything inside changes together in one transaction. A repository per table breaks the boundary, because each repository commits its own part.
Intended: Api -> Application -> Domain Infrastructure -> Application
Actual: Application -> Infrastructure (cycle risk, EF Core everywhere)
The moment Application uses AppDbContext concretely, use cases can't be tested without EF Core, and Infrastructure changes ripple into handlers.
Request → Command → Entity → Dto → Response means four object graphs per call, and convention-based mappers fail silently: rename Qty to Quantity on one side and the value becomes 0 without a compile error. For reads, a single Select projection in the query produces the response directly and only fetches needed columns. For writes, explicit mapping (or a source generator such as Mapperly) gives compile-time safety.
An interface is worth it when it marks a seam: a boundary to infrastructure, a place you substitute in tests, or a genuine strategy. IAddLineHandler with one implementation, resolved only by an endpoint, is none of these.
order.Status = "Shipped" then adds a line via the current handler; see that it succeeds.AddLine; watch the compiler find every rule-breaking call site.SaveChanges calls and inspect the database state.AssertConfigurationIsValid — note the silent null.The rewrite: a rich aggregate, a port for the aggregate root, a handler that saves once, and a read projection.
// Domain/Orders/Order.cs
namespace Shop.Domain.Orders;
public sealed class Order
{
private readonly List<OrderLine> _lines = [];
private Order() { }
public Guid Id { get; private set; } = Guid.NewGuid();
public OrderStatus Status { get; private set; } = OrderStatus.Draft;
public IReadOnlyList<OrderLine> Lines => _lines;
public decimal Total => _lines.Sum(l => l.UnitPrice * l.Quantity); // derived, can't drift
public static Order Create() => new();
public Result AddLine(string sku, int quantity, decimal unitPrice)
{
if (Status != OrderStatus.Draft) return Result.Fail("Only draft orders can be changed.");
if (quantity <= 0) return Result.Fail("Quantity must be positive.");
_lines.Add(new OrderLine(sku, quantity, unitPrice));
return Result.Ok();
}
}
public sealed record OrderLine(string Sku, int Quantity, decimal UnitPrice);
public enum OrderStatus { Draft, Placed, Shipped }
public readonly record struct Result(bool Succeeded, string? Error)
{
public static Result Ok() => new(true, null);
public static Result Fail(string error) => new(false, error);
}
// Application/Orders/AddLine.cs — no reference to Infrastructure
namespace Shop.Application.Orders;
using Shop.Domain.Orders;
public interface IOrderRepository // one per aggregate root; a real seam to persistence
{
Task<Order?> GetAsync(Guid id, CancellationToken ct);
Task SaveChangesAsync(CancellationToken ct); // one transaction for the whole aggregate
}
public sealed record AddLineCommand(Guid OrderId, string Sku, int Quantity, decimal UnitPrice);
public sealed class AddLineHandler(IOrderRepository orders) // no IAddLineHandler: nothing substitutes it
{
public async Task<Result> HandleAsync(AddLineCommand cmd, CancellationToken ct)
{
var order = await orders.GetAsync(cmd.OrderId, ct);
if (order is null) return Result.Fail("Order not found.");
var result = order.AddLine(cmd.Sku, cmd.Quantity, cmd.UnitPrice);
if (result.Succeeded) await orders.SaveChangesAsync(ct);
return result;
}
}
// Infrastructure/Queries/OrderSummaryQuery.cs — reads project straight to the response, no mapping chain
namespace Shop.Infrastructure.Queries;
using Microsoft.EntityFrameworkCore;
public sealed record OrderSummaryResponse(Guid Id, string Status, int LineCount, decimal Total);
public sealed class OrderSummaryQuery(ShopDbContext db)
{
public Task<OrderSummaryResponse?> GetAsync(Guid id, CancellationToken ct) =>
db.Orders.AsNoTracking()
.Where(o => o.Id == id)
.Select(o => new OrderSummaryResponse(
o.Id, o.Status.ToString(), o.Lines.Count, o.Lines.Sum(l => l.UnitPrice * l.Quantity)))
.SingleOrDefaultAsync(ct);
}
The EF Core mapping for Lines (OwnsMany or a separate entity with a backing field) lives in an IEntityTypeConfiguration<Order> in Infrastructure, keeping the domain persistence-ignorant.
DbContext directly in handlers.Cargo-cult Clean Architecture is common because templates make the folders free and the thinking optional. A senior reviewer asks "what does each layer protect?" If the domain protects no invariants, the layering is pure cost. I push for a rich model where rules are complex, simplicity where they aren't, and mechanical enforcement of whatever we keep. I also manage the human side: one worked example beats forty comments, and an ADR turns a review into a team decision.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Fix in place (rich aggregates, fewer layers) | Domain has real rules; team open to change | Two or three sprints of incremental work | Service scheduled for retirement |
| Simplify to vertical slices | Mostly CRUD with few shared rules | Restructuring folders and DI | Complex shared invariants |
| Leave structure, add tests only | Low-change legacy area | Low | Active development where bugs keep appearing |
I measure the outcome by bugs in the affected area, mapping profiles and files per feature, and handler test speed.
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.
A repository gives the domain a collection-like interface for one aggregate root: GetAsync(orderId), Add(order). The domain asks for orders; it doesn't know about SQL, DbContext or tables. That's different from a DAO/table gateway, which mirrors tables with CRUD per table.
In EF Core, DbContext already is a repository (DbSet<T>) and a unit of work (SaveChanges). So a generic IRepository<T> with GetAll(), Update() and Save() usually adds a layer with no behaviour, and makes things worse:
IQueryable<T> GetAll() leaks EF semantics to callers.Save() per repository breaks the unit of work.A good repository is narrow and aggregate-specific, takes a CancellationToken and never commits. The trade-off is an abstraction that protects the domain model, against a layer that only renames EF Core.
The Mapper pattern keeps two models (entity and DTO) apart by putting the conversion in one place. In .NET 10 there are three common options:
ProjectTo. Since v15.0 (July 2025) it's dual-licensed RPL-1.5/commercial (Lucky Penny Software), free for companies under US$5M revenue.IQueryable projections.The bigger win is often where you map. Projecting with Select in the query fetches only the needed columns, skips tracking and avoids lazy-loading N+1. Loading entities and mapping them afterwards over-fetches. The trade-off is convenience against explicitness, licence cost and run-time surprises.
How to tell it (STAR)
**S:** On [our order service], about [15] orders a month were being changed after dispatch. **T:** I was asked to review the code and fix the cause, not just the symptom. **A:** I found the rules lived in three handlers, two without a status check, and table-shaped repositories committing separately. I ranked the review by data impact, rewrote the `Order` aggregate as a worked example, added architecture tests with a baseline, and wrote an ADR the team agreed in a short session. **R:** After-dispatch edits dropped to [zero], mapping profiles went from [62] to [9], and the team applied the same pattern to [two] more aggregates on their own.
Last updated 23 Nov 2026.