Clean Architecture
Clean Architecture keeps core business rules independent from frameworks, databases, transport protocols, and user interfaces.
Overview
Clean Architecture separates stable business policy from volatile delivery and infrastructure details by enforcing an inward dependency direction. Domain types own business invariants; application use cases coordinate those types through explicit ports; outer adapters translate HTTP, persistence, messaging, clocks, identity, and other environment concerns. The objective is not a ceremonial number of projects, repositories, or interfaces. A boundary earns its place when it protects meaningful policy, enables independent testing, or isolates a real source of change. Compile-time project references, internal visibility, architecture tests, and a single composition root can make dependency rules executable. Teams must still design transaction boundaries, authorization, idempotency, validation placement, observability, and failure semantics explicitly. Clean Architecture can coexist with feature folders, vertical slices, DDD, or a modular monolith; it describes dependency direction rather than a universal folder template.
What you will learn
- Explain the dependency rule and distinguish policy from implementation detail.
- Place domain invariants, use-case orchestration, input validation, and adapter translation deliberately.
- Define narrow ports without mirroring a framework API mechanically.
- Compose and test a use case without a database, web host, or wall clock.
- Enforce dependency direction with project references and architecture tests.
- Evolve persistence and delivery adapters without leaking their models inward.
Prerequisites
- C# dependency injection, interfaces, records, async workflows, and automated testing.
- Basic domain modeling, HTTP APIs, persistence, transactions, and cancellation.
- Understanding that architecture optimizes change and risk rather than folder symmetry.
When to use Clean Architecture
Good fit
- Core business policy must outlive or be testable apart from frameworks and storage.
- Several delivery mechanisms or infrastructure adapters execute the same use cases.
- The codebase is large enough that enforceable dependency direction reduces change risk.
Choose another approach when
- A small CRUD utility has no meaningful policy to protect and direct framework code is clearer.
- Interfaces only duplicate every ORM or SDK method without isolating a decision.
- The team would add layers by template while allowing domain behavior to remain anemic and coupled.
Key concepts
Source-code dependencies point toward policies; inner layers do not reference outer implementation details.
Application services coordinate domain behavior, authorization context, persistence ports, and outcomes.
Interfaces define required capabilities while outer adapters implement HTTP, database, or message integration.
Entities and value objects enforce business invariants without depending on delivery frameworks.
One outer location selects concrete adapters, configuration, decorators, and lifetimes without leaking those choices inward.
Commands, results, ports, and errors express use-case needs rather than exposing HTTP, ORM, or vendor-specific types.
The application boundary defines consistency and commit behavior; repositories do not each create hidden transactions.
Project references, internal visibility, dependency tests, and code review turn intended arrows into verifiable constraints.
Architecture
External adapters depend on application ports, and application orchestration depends on the domain—not the reverse.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
The dedicated order sample starts from one business use case, places invariants in domain types, expresses persistence and time as application ports, and selects in-memory adapters only at the composition root.
- 01Identify policy and actors
Describe the use case, business invariants, authorization context, accepted inputs, explicit outcomes, and consistency boundary.
- 02Model the domain
Create behavior-rich entities and value objects that reject invalid state without framework dependencies.
- 03Define the application boundary
Add a command, result, handler, and only the ports required to complete the use case.
- 04Implement adapters
Translate HTTP, persistence, messaging, identity, and time into application contracts at the outside edge.
- 05Compose dependencies
Register concrete adapters, decorators, policies, configuration, and lifetimes in one composition root.
- 06Test policy and boundaries
Use fakes for fast use-case tests and targeted integration tests for each real adapter and transaction.
- 07Enforce and evolve
Fail builds on forbidden dependencies and change a framework or adapter to prove the boundary remains useful.
Code example
A use case coordinates policy through ports without knowing whether input arrived over HTTP or where data is stored.
public sealed class PlaceOrderHandler(
IOrderRepository orders,
IUnitOfWork unitOfWork,
IClock clock)
{
public async Task<Guid> HandleAsync(PlaceOrder command, CancellationToken ct)
{
var order = Order.Place(command.CustomerId, command.Lines, clock.UtcNow);
await orders.AddAsync(order, ct);
await unitOfWork.SaveChangesAsync(ct);
return order.Id;
}
}Testing strategy
Test inward policy directly and test adapters at their real boundaries.
- Unit-test domain invariants with no container, database, clock, or network.
- Test application handlers through ports and deterministic fakes.
- Integration-test persistence mapping, transactions, concurrency, and migrations against the real provider.
- Exercise HTTP contracts, authentication, authorization, cancellation, and Problem Details through the host.
- Add architecture tests for forbidden domain-to-infrastructure and application-to-web references.
- Verify failures do not commit partial state or publish events prematurely.
Security considerations
Architectural separation does not automatically enforce security; identity and authorization context must enter through trusted adapters and be applied inside the use case.
- Authenticate at the delivery edge and pass a minimal trusted actor context inward.
- Authorize the requested action and resource inside the use-case boundary, not only by route.
- Never let callers choose tenant, owner, role, or raw persistence filters unchecked.
- Keep secrets and vendor credentials in outer configuration and redact sensitive failures.
- Return stable application errors and map them to non-disclosing transport responses.
Performance and scalability
Every boundary has a cognitive and runtime cost, so measure hot paths and avoid abstractions that add no policy value.
- Keep domain and handler calls in process and allocation-conscious on hot paths.
- Use projection ports for read-heavy queries rather than loading rich aggregates unnecessarily.
- Make database round trips and transaction scope visible in the use case.
- Propagate cancellation and avoid sync-over-async adapters.
- Benchmark mapping and decorators only when profiles show material cost.
Deployment and operations
Deploy the composed application as one unit while keeping adapter configuration and migrations explicit.
- Validate configuration and adapter availability at startup.
- Apply backward-compatible database migrations through a controlled deployment step.
- Register production adapters explicitly and prohibit accidental in-memory fallbacks.
- Emit traces and metrics around use cases, outbound ports, and transaction outcomes.
- Smoke-test the deployed transport through a real adapter to the system of record.
Common problems and fixes
A simple change touches every project.
Likely cause: Layers mirror technical steps instead of protecting cohesive policy.
Fix: Reshape around use cases and remove pass-through abstractions.
Domain code references EF Core or ASP.NET types.
Likely cause: Persistence and transport models crossed the inward boundary.
Fix: Map at adapters and enforce project reference rules.
Tests require a full host for business rules.
Likely cause: Time, persistence, identity, or messaging are hidden static dependencies.
Fix: Expose narrow application ports and inject deterministic fakes.
Repositories contain business workflows.
Likely cause: The application boundary is anemic or transaction ownership is unclear.
Fix: Move orchestration to named use cases and keep repositories focused on required persistence capabilities.
Interfaces change whenever a vendor SDK changes.
Likely cause: Ports mirror the adapter rather than application needs.
Fix: Redesign ports in business language and translate in the adapter.
Events publish for rolled-back work.
Likely cause: Persistence and publication are not coordinated.
Fix: Define transaction ownership and use an outbox where durable messaging is required.
Best practices
- Introduce a boundary when it protects a meaningful policy or source of change.
- Keep domain invariants inside domain types, not only in controllers or validators.
- Name use cases in business language and return explicit outcomes.
- Test architecture rules automatically if dependency direction is important.
- Keep framework, ORM, identity, and vendor types at outer adapters.
- Own transaction and event-publication semantics at the application boundary.
- Use focused query models when rich domain loading adds no value.
- Delete pass-through abstractions that make behavior harder to follow.
Production checklist
- Domain and application projects have no delivery or infrastructure references.
- Business invariants live in domain behavior and use-case preconditions are explicit.
- Ports express application needs and do not mirror whole frameworks.
- One composition root selects production adapters and validates configuration.
- Authorization, transaction, idempotency, cancellation, and error semantics are defined per use case.
- Unit, adapter integration, transport, and architecture tests cover different risks.
- Observability identifies use cases and ports without leaking sensitive data.
- A documented decision explains which boundaries exist and what change pressure they protect.
Common interview questions
What is the dependency rule?
Dependencies should point inward toward higher-level policy, so domain and application code do not depend on UI, database, or framework details.
Does every project need four class-library projects?
No. Project layout is a tool. Small applications can preserve boundaries with namespaces and tests; larger systems may benefit from compile-time project separation.
Where should validation live?
Input-shape validation belongs near the boundary; business invariants belong in the domain; use-case preconditions belong in the application layer.
Where should database transactions be controlled?
The application use case should define the consistency boundary while the infrastructure adapter implements it; independent repository commits make partial outcomes likely.
How is Clean Architecture different from Vertical Slice Architecture?
Clean Architecture governs dependency direction and policy isolation. Vertical slices organize code by behavior. A system can use both.
When is a repository abstraction harmful?
When it merely duplicates an ORM, hides useful query capabilities, or introduces indirection without protecting an application-specific contract.
How do you publish integration events safely?
Record the event or outbox entry in the same transaction as state, then deliver asynchronously with idempotent consumers.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
Clean Architecture Orders
A .NET 10 order workflow demonstrating inward dependency direction, domain invariants, application ports, replaceable adapters, deterministic tests, and a single composition root.
- Run
dotnet run --project src/CleanArchitectureOrders- Test
dotnet test CleanArchitectureOrders.slnx