Layered and clean architecture
Layered and clean architecture
Clean Architecture separates business policy from delivery and persistence details. The important rule is which code depends on which other code at compile time, not the number or names of folders.
A typical layered application separates presentation, business logic and data access; dependency direction may still point from business code toward a concrete database. Clean Architecture places domain and use cases near the center, with outer infrastructure implementing ports owned by the inner layers. Hexagonal architecture expresses similar ideas as ports and adapters; vertical slices group code around a use case and can apply the same dependency rules without global service layers. Composition root is the boundary that wires concrete objects, usually in the executable or startup. A repository port can express domain operations or a precise persistence contract; a generic CRUD repository over every entity may duplicate EF Core features and hide transaction needs. An application service coordinates authorization, domain operations, persistence and response mapping; it does not replace business invariants with DTO validation. A DTO is a transport shape, not a mutable domain entity. Keep mapping explicit, and enforce tenant access and concurrency in the persistence path. A fake adapter is useful for policy tests but cannot establish database constraints, transaction isolation or translation. The examples below use in-memory state or pure mapping; the companion multi-project lab demonstrates actual project-reference direction without a database.
Baseline: .NET 10 / C# 14. All C# results below are reasoned, not executed. Offline models and multi-project labs are explicitly distinguished.
Define a port where the use case needs it
The use case asks for an order total through a minimal read interface. The adapter here is deterministic and does not access a database.
Use the archived Fixture.csproj with an approved .NET 10 SDK. No third-party packages are required. Inspect the project, then build and run with the approved SDK.
using System;var useCase = new GetTotal(new FixedOrders());Console.WriteLine(useCase.Execute("A"));Console.WriteLine(useCase.Execute("missing") is null);interface IOrderTotals { int? FindCents(string orderId); }sealed class GetTotal(IOrderTotals totals) { public int? Execute(string id) => totals.FindCents(id); }sealed class FixedOrders : IOrderTotals { public int? FindCents(string orderId) => orderId == "A" ? 1250 : null; }Expected result (not executed):
1250TrueThe inner contract represents a use case need, not a database API. The outer caller selects FixedOrders. A real port must also define tenant, cancellation and failure semantics.
Map the domain result to a transport DTO
The internal cost is excluded from a public order summary. This is projection, not a substitute for authorization.
Use the archived Fixture.csproj with an approved .NET 10 SDK. No third-party packages are required. Inspect the project, then build and run with the approved SDK.
using System;var model = new OrderSummary("A", 1250, 800);var dto = new OrderDto(model.Id, model.TotalCents);Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(dto));sealed record OrderSummary(string Id, int TotalCents, int InternalCostCents);sealed record OrderDto(string Id, int TotalCents);Expected result (not executed):
{"Id":"A","TotalCents":1250}The serializer sees only the DTO fields. Test the actual HTTP JSON options separately, because an ASP.NET Core web default may use camelCase. Authorization is still required before selecting the model.
Test orchestration and failed persistence separately
A fake write port deliberately rejects one save. The use case returns success only when the port reports success. This is a contract test, not a transactional database test.
Use the archived Fixture.csproj with an approved .NET 10 SDK. No third-party packages are required. Inspect the project, then build and run with the approved SDK.
using System;foreach (bool canSave in new[] { true, false }) { var store = new TestStore(canSave); var useCase = new PlaceOrder(store); Console.WriteLine($"{useCase.Execute(2)}: {store.Writes}"); Console.WriteLine($"{useCase.Execute(0)}: {store.Writes}");}interface IOrders { bool TryAdd(int units); }sealed class PlaceOrder(IOrders store) { public bool Execute(int units) => units > 0 && store.TryAdd(units);}sealed class TestStore(bool canSave) : IOrders { public int Writes { get; private set; } public bool TryAdd(int units) { if (!canSave) return false; Writes++; return true; }}Expected result (not executed):
True: 1False: 1False: 0False: 0A failed validation skips the port. A rejected persistence call does not increment the stored-write count. Real implementations should distinguish conflict, validation, cancellation and transient failure instead of flattening everything to bool.
Apply the concept
Sketch projects for a PlaceOrder use case, including a domain project, use-case project, SQL adapter and web host. Explain how to test each dependency direction and transaction.
Use the manual practice and knowledge check. Do not deploy or publish these fixtures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Layered and clean architecture — knowledge check
Apply the lesson concepts to the following scenarios.
Which direction should the SQL adapter depend on in Clean Architecture?
What belongs in the composition root?
What does a fake repository test establish?
Why project a domain entity into a DTO?
What is a vertical slice?