Covers the dependency rules of layered architecture, strict versus relaxed layering, and the common failure modes: database-centric design, leaky layers, pass-through layers and the anaemic domain.
The core rule: a layer may only depend on layers below it — presentation → business → data — never upwards and never in a cycle.
IQueryable, EF entities, SqlException in controllers.The trade-off: layering is simple and familiar, but every feature cuts across all layers and the domain ends up depending on the database.
"The rule in a layered architecture is that dependencies only point down. Presentation may call the business layer, the business layer may call data access, and nothing below may know about anything above. In .NET I make the compiler enforce that with project references:
WebreferencesBusiness,BusinessreferencesData, and a reference the other way would create a cycle. Within that, there are two variants: strict layering, where you can only call the layer directly below, and relaxed layering, where a controller may skip straight to data access for a simple read. Relaxed is pragmatic, but each skip should be a conscious choice.The problems appear as the system grows. The first is database-centric design: because data access is at the bottom, people design tables first, generate entities, and the business layer becomes a set of services that load rows, change fields and save them. Rules end up scattered across services and stored procedures. The second is leaky layers: the data layer returns
IQueryable<Order>or EF entities, so the controller ends up composing queries and serialising entities with navigation properties — and now the UI depends on the schema. The third is the sinkhole: three layers where most requests just map a DTO to another DTO and pass it down, adding code without adding behaviour.The mistake I see is blaming layering itself. Layering is fine for CRUD-heavy apps. What hurts is letting the database sit at the centre of a complex domain; that's exactly the dependency Clean and Hexagonal architectures invert."
| Rule | Meaning | How .NET enforces it |
|---|---|---|
| Downward only | Higher layers depend on lower ones | Project references; the compiler rejects circular references |
| No skipping (strict) | Only the next layer down | Not enforced by the compiler — needs architecture tests |
| Hide internals | Each layer exposes a small public surface | internal types, InternalsVisibleTo only for tests |
| Strict | Relaxed | |
|---|---|---|
| Calls allowed | Next layer only | Any lower layer |
| Benefit | Changes stay local | Less pass-through code |
| Cost | Sinkhole layers, more mapping | Easier to couple UI to data |
| Good for | Systems with real rules in the middle | Read-heavy, CRUD-heavy apps |
| Problem | Symptom in code | Consequence |
|---|---|---|
| Database-centric design | Entities generated from tables; services named OrderTableService |
Rules scattered; schema changes ripple everywhere |
| Leaky layer | IQueryable<T> or EF entities returned to controllers; DbUpdateException caught in controllers |
UI coupled to schema; N+1 queries from serialisation |
| Sinkhole | OrderController → OrderService → OrderRepository each one line long |
Code with no behaviour, triple maintenance |
| Anaemic domain | Entities with only public getters/setters, logic in *Service classes |
Invariants enforced in many places, or nowhere |
| Cross-cutting features | One feature edits files in every layer | Merge conflicts, slow change |
A booking API returned EF entities from its data layer straight to controllers. A new navigation property caused System.Text.Json to serialise the whole graph, and one endpoint started issuing 120 lazy-loading queries per request — p95 rose from 80 ms to 1.9 s. Returning projected DTOs from the data layer, and switching lazy loading off, brought it back to 70 ms.
Checks that the candidate knows the dependency rules of layering and can recognise the problems it causes in real codebases.
Green flags
IQueryable<T> or entities in controllersRed flags
DbContext directly is always fine in a complex domainIf A depends on B, a change to B can break A, but not the other way round. Pointing all dependencies one way means the bottom layers are the most stable and the top layers the most volatile. Cycles destroy that: change anything in the cycle and everything in it may break.
Presentation --> Business --> Data --> SQL Server
(volatile) (stable?)
The catch in the classic layout: data access is at the bottom, so the business layer depends on it. Your most important code (the rules) depends on your most technical code (EF Core, SQL).
Strict: Relaxed:
Web -> Business -> Data Web -> Business -> Data
Web -------------> Data (allowed skip)
The compiler can't tell these apart — both are just project references. Only an architecture test (NetArchTest, ArchUnitNET) or a code review rule can stop Web from using Data in a strict design.
A layer leaks when its implementation details become part of its contract:
IQueryable<T>: the caller can add Where, Include and Skip, so the query is really built in the controller and the data layer's performance guarantees are gone.SqlException number 2627 (unique key violation) caught in a controller ties HTTP code to SQL Server.[Column] attributes and virtual navigation properties for lazy loading.The typical path:
dotnet ef dbcontext scaffold).SaveChanges.The result: every rule ("an order can't be cancelled after dispatch") lives in whatever service happens to change that field. Two services can change it two different ways. This is the anaemic domain model Martin Fowler described.
Layers are horizontal slices, but features are vertical. Adding "order notes" touches the controller, the DTO, the service, the repository, the entity and the migration. That is why Vertical Slice Architecture groups code by feature instead.
IQueryable<Order> from a repository, add .Include(o => o.Lines) in the controller, and see the generated SQL in the EF Core logs.LogTo(Console.WriteLine).Web doesn't reference Data (strict layering).A leaky data layer and the fixed version: the contract exposes results, not query machinery.
// Before: the data layer leaks EF Core upwards.
namespace Shop.Data;
public sealed class LeakyOrderRepository(ShopDbContext db)
{
// The caller can compose anything onto this, including Include and ToList on huge tables.
public IQueryable<Order> Query() => db.Orders;
}
// Controller in Shop.Web now depends on EF Core and the schema:
// var orders = repo.Query().Include(o => o.Lines).Where(o => o.Status == "Open").ToList();
// After: the data layer returns exactly what the use case needs.
namespace Shop.Data;
public sealed record OpenOrderDto(int Id, string Customer, decimal Total, int LineCount);
public interface IOrderQueries
{
Task<IReadOnlyList<OpenOrderDto>> GetOpenOrdersAsync(int page, int pageSize, CancellationToken ct);
}
internal sealed class OrderQueries(ShopDbContext db) : IOrderQueries
{
public async Task<IReadOnlyList<OpenOrderDto>> GetOpenOrdersAsync(int page, int pageSize, CancellationToken ct) =>
await db.Orders
.AsNoTracking()
.Where(o => o.Status == OrderStatus.Open)
.OrderBy(o => o.Id)
.Skip((page - 1) * pageSize)
.Take(pageSize)
// Projection: one SQL query, no entities or navigation properties leave this layer.
.Select(o => new OpenOrderDto(o.Id, o.CustomerName, o.Total, o.Lines.Count))
.ToListAsync(ct);
}
// Shop.Data/DependencyInjection.cs — the implementation stays internal; only the interface is public.
namespace Shop.Data;
using Microsoft.Extensions.DependencyInjection;
public static class DependencyInjection
{
public static IServiceCollection AddShopData(this IServiceCollection services)
{
services.AddScoped<IOrderQueries, OrderQueries>();
return services;
}
}
IQueryable<T> from the data layer. Why it is wrong: query construction moves into callers, so performance and correctness can't be reasoned about in one place. Instead: return materialised results or DTOs from purpose-built methods.SqlException or DbUpdateException in controllers. Why it is wrong: HTTP code now depends on the database provider. Instead: translate to a domain or application error in the lower layer.Layered architecture isn't wrong; it is a fit for simple, data-shaped domains. Its real flaw is that the business layer depends on data access, so the core of the system depends on its most volatile technology. When the domain has meaningful rules, I invert that dependency (Clean or Hexagonal) and model behaviour first with DDD tactics — entities that enforce their own invariants, aggregates as consistency boundaries — so persistence follows the model instead of shaping it. When it's mostly CRUD, I relax the layering or organise by feature, using CQRS-style read handlers that project straight to DTOs, to kill the sinkholes.
Whatever I choose, I make it enforced, not remembered: project references for direction, internal for implementation types, and a handful of architecture tests in CI ("Web must not reference Data", "no type outside Data uses DbContext"). That turns a layering decision into a fitness function that fails the build.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Strict layering | Real rules in the business layer | Pass-through code, more mapping | CRUD screens with no rules |
| Relaxed layering | Read-heavy, simple apps | Easier to couple UI to schema | Complex rules that must not be bypassed |
| Inverted (Clean/Hexagonal) + rich domain | Complex domain, long-lived system | More projects and interfaces | Small, short-lived apps |
| Vertical slices + CQRS reads | Many independent features | Less shared structure | Rules shared across many features |
A cheap health check: count how many projects a typical feature touches and how many layers contain no logic. Both numbers tell you whether the layering is paying for itself.
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.
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.
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.
Last updated 23 Nov 2026.