clean-architecture-dotnet
Use when domain logic leaks into API/Infrastructure, project references violate layer boundaries, or CQRS handlers/buses need implementation.
- License 许可
- MIT
- 最近更新
- 2026-05-29
- Stars
- ★ 1
- Forks
- 0
01 前言 Front Matter
- name
- clean-architecture-dotnet
- metadata
- { "authors": [ "Sébastien DEGODEZ" ], "version": 2 }
- description
- Use when domain logic leaks into API/Infrastructure, project references violate layer boundaries, or CQRS handlers/buses need implementation.
02 资源文件 25
- 参考文档references/architecture-layers.md1.6 KB
- 参考文档references/convention-based-di.md10.6 KB
- 参考文档references/cqrs-patterns.md3.1 KB
- 参考文档references/ddd.md10.3 KB
- 参考文档references/layer-responsibilities.md14.2 KB
- 参考文档references/netarchtest-rules.md10.4 KB
- 参考文档references/project-structure.md1.7 KB
- 参考文档references/shared-kernel.md5.7 KB
- 脚本scripts/init-project.ps115.3 KB
- 脚本scripts/init-project.sh7.2 KB
- 其他templates/Api/IApiMarker.cs182 B
- 其他templates/Application/IApplicationMarker.cs214 B
- 其他templates/Application/Shared/ICommandBus.cs378 B
- 其他templates/Application/Shared/ICommandHandler.cs517 B
- 其他templates/Application/Shared/IQueryBus.cs268 B
- 其他templates/Application/Shared/IQueryHandler.cs267 B
- 其他templates/Domain/IDomainMarker.cs194 B
- 其他templates/Infrastructure/CQRS/CommandBus.cs1.1 KB
- 其他templates/Infrastructure/CQRS/QueryBus.cs792 B
- 其他templates/Infrastructure/DependencyInjection.cs1.8 KB
- 其他templates/Infrastructure/IInfrastructureMarker.cs226 B
- 其他templates/IntegrationTests/ArchitectureTests.cs4.4 KB
- 参考文档tests/baseline-prompts.txt2.2 KB
- 参考文档tests/README.md3.8 KB
- 参考文档tests/validation.md18.0 KB
03 SKILL.md 正文
Clean Architecture in .NET
Overview
Clean Architecture organizes code into independent layers (Domain → Application → Infrastructure → API).
The Iron Law: Violating layer boundaries is a failure. If API references Application or Domain references Infrastructure, delete the change and start over.
When to Use
- Business logic is leaking into Controllers or Repositories
- Circular dependencies occur between projects
- Need to isolate core business rules from external frameworks (EF Core, APIs)
- Autonomy is required: sealed Domain objects, strongly-typed IDs
DDD vs POCO — Quick Decision
| Use | When |
|---|---|
sealed class Foo : AggregateRoot + factory method |
The object has domain invariants, raises events, or owns child entities |
Plain sealed record Foo(...) (POCO) |
Pure data carrier, no invariants, used only inside Application or API (DTOs, ViewModels) |
sealed class Bar : ValueObject |
Immutable, identity-by-value, represents a domain concept (e.g., PolicyNumber, Horsepower) |
Rule of thumb: if you're tempted to add an if or throw to protect the object's state — it's a Domain object (aggregate or value object), not a POCO.
Implementation Flow
digraph clean_arch {
"New Feature?" [shape=diamond];
"Define Logic in Domain" [shape=box];
"Create Handler in Application" [shape=box];
"Inject Handler in API" [shape=box];
"New Feature?" -> "Define Logic in Domain" [label="Business Rule"];
"New Feature?" -> "Create Handler in Application" [label="Orchestration Only"];
"Define Logic in Domain" -> "Create Handler in Application";
"Create Handler in Application" -> "Inject Handler in API";
}
Core Pattern (CQRS)
Commands (writes) and Queries (reads) separate side-effects:
// Application/Features/Orders/PlaceOrderCommandHandler.cs
public sealed class PlaceOrderCommandHandler : ICommandHandler<PlaceOrderCommand, OrderId>
{
private readonly IOrderRepository _repository; // Interface defined in Application/Domain
public async Task<OrderId> HandleAsync(PlaceOrderCommand cmd, CancellationToken ct)
{
var order = Order.Create(cmd.OrderId, cmd.CustomerName);
await _repository.AddAsync(order, ct);
return order.Id;
}
}
// API/OrdersEndpoints.cs — inject ICommandBus (never ICommandHandler<,> directly)
app.MapPost("/orders", async (PlaceOrderCommand cmd, ICommandBus bus)
=> Results.Created($"/orders/{await bus.PublishAsync<PlaceOrderCommand, OrderId>(cmd)}"));
// Queries follow the same rule — inject IQueryBus
app.MapGet("/orders/{id}", async (Guid id, IQueryBus bus)
=> Results.Ok(await bus.SendAsync<GetOrderQuery, OrderViewModel>(new GetOrderQuery(new OrderId(id)))));
// Both buses resolve via Infrastructure DI. API never references Application assembly.
Layer Responsibilities
| Layer | Purpose | Allowed Dependencies |
|---|---|---|
| SharedKernel (multi-context only) | Generic interfaces + base classes only — zero domain logic | None |
| Domain | Pure business logic, aggregates | SharedKernel (optional) |
| Application | Use cases, Handler orchestration | Domain, SharedKernel (optional) |
| Infrastructure | Database, DI registration, CQRS Bus | Application, Domain |
| API | Endpoints, JSON mapping | Infrastructure (Transitive: Application, Domain) |
Shared Kernel (Multi-Context Solutions)
Use a SharedKernel project when two or more Bounded Contexts need to share handler interfaces or base classes. It must contain zero domain logic.
SharedKernel/
├── Abstractions/
│ ├── ICommandHandler.cs ← generic interface only
│ ├── IQueryHandler.cs
│ ├── ValueObject.cs ← base class, no business logic
│ └── AggregateRoot.cs ← base class, exposes DomainEvents collection
└── Events/
└── DomainEvent.cs ← abstract base for all domain events
Dependency rule for SharedKernel: it depends on nothing. Domain and Application reference it, not the other way around.
// SharedKernel/Abstractions/ICommandHandler.cs — pure interface, no NuGet beyond System
public interface ICommandHandler<in TCommand, TResult>
{
Task<TResult> HandleAsync(TCommand command, CancellationToken ct = default);
}
// Each context's Application layer implements it:
// Orders.Application/Features/PlaceOrder/PlaceOrderCommandHandler.cs
using SharedKernel.Abstractions;
public sealed class PlaceOrderCommandHandler
: ICommandHandler<PlaceOrderCommand, OrderId> { }
What NEVER goes in SharedKernel: concrete value objects like Money, Address (each context defines its own); aggregate logic; context-specific event types.
Domain Events
Rule: Domain events are declared in the Domain layer and dispatched in the Application layer (from the handler, after the aggregate operation succeeds).
// Domain/Orders/Events/OrderPlacedEvent.cs — sealed, in Domain
public sealed class OrderPlacedEvent : DomainEvent // DomainEvent base from SharedKernel (or Domain if single-context)
{
public OrderId OrderId { get; }
public OrderPlacedEvent(OrderId orderId) => OrderId = orderId;
}
// Domain/Orders/Order.cs — aggregate raises the event
public sealed class Order : AggregateRoot
{
public static Order Create(OrderId id, CustomerId customerId)
{
var order = new Order(id, customerId);
order.AddDomainEvent(new OrderPlacedEvent(id)); // ← raised in Domain
return order;
}
}
// Application/Features/PlaceOrder/PlaceOrderCommandHandler.cs — handler dispatches
public sealed class PlaceOrderCommandHandler : ICommandHandler<PlaceOrderCommand, OrderId>
{
private readonly IOrderRepository _repository;
private readonly IDomainEventDispatcher _dispatcher; // interface in Application/Domain
public async Task<OrderId> HandleAsync(PlaceOrderCommand cmd, CancellationToken ct)
{
var order = Order.Create(cmd.OrderId, cmd.CustomerId);
await _repository.AddAsync(order, ct);
await _dispatcher.DispatchAsync(order.DomainEvents, ct); // ← dispatched in Application
return order.Id;
}
}
Anti-pattern: Never dispatch events from inside a Domain aggregate method — Domain has no dependency on dispatch infrastructure.
The Dependency Chain (Transitive Access)
The architecture follows a strict outward-in dependency flow: API → Infrastructure → Application → Domain
- API has access to everything below it (Infrastructure, Application, Domain).
- Infrastructure has access to Application and Domain.
- Application has access to Domain.
- Domain remains pure with zero project dependencies.
CRITICAL: Just because a layer can see another via transitive reference doesn't mean it should use its concrete types.
- API should only use Interfaces from Application/Domain.
- Always follow the Iron Law and Red Flags below.
Rationalization Table
| Excuse | Reality |
|---|---|
| "Injecting ICommandHandler<,> directly is simpler" | Always use ICommandBus / IQueryBus — consistent indirection, easier to intercept (logging, validation). |
| "It's just one small service" | Small leaks become circular dependency nightmares. |
| "Referencing Application in API is faster" | It bypasses the Bus/Handler pattern and couples contract to implementation. |
| "Domain needs this NuGet package" | If it's not a primitive/System lib, it doesn't belong in Domain. |
Red Flags - STOP and Start Over
using MyApp.Application;inside API layer filesusing MyApp.Infrastructure;inside Domain layer files- Injecting
ICommandHandler<,>orIQueryHandler<,>directly in API endpoints — useICommandBus/IQueryBus - Non-sealed classes in Domain
- Handlers performing HTTP calls directly (use an Infrastructure service via interface)
Common Mistakes
| Mistake | Fix |
|---|---|
| Handler not found by DI | Handler must be listed explicitly in AddInfrastructure() via AddHandler<T>() |
using MyApp.Application; in API |
Remove it — inject ICommandBus / IQueryBus via DI |
Guid used in handler return type |
Use strongly typed ID (OrderId, ProductId) |
Read result named ProductDto |
Name it ProductViewModel to distinguish from transfer objects |
typeof(Product).Assembly in tests |
Use typeof(IApplicationMarker).Assembly for reliable discovery |
| Non-sealed Domain classes | All Domain classes must be sealed (enforced by NetArchTest) |
| SharedKernel references Domain | SharedKernel must depend on nothing — if it references Domain, invert: Domain references SharedKernel |
Handler contains if/business logic |
Delegate to Domain aggregate methods — handlers orchestrate only |
References
- Architecture Layers — Dependency rules, marker interfaces, layer tests, and layer validation with NetArchTest
- CQRS Patterns — Handler interfaces, examples, DI discovery, and complete CQRS implementation patterns
- Convention-Based DI — Auto-discovery, Bus interfaces, full DI setup
- Layer Responsibilities — Full rules for each layer with DDD context
- Project Structure — File/folder conventions and layer organization guidance
- NetArchTest Rules — Automated boundary enforcement
- DDD Patterns — Aggregates, factory methods, value objects, and domain events (optional)
- Shared Kernel — Shared abstractions for multi-context solutions (optional)
- Init Script — Bootstrap script for new project setup (
./init-project.sh MyApp) - ArchitectureTests Template — Drop-in architecture test template
04 同仓库更多 Skills
writing-clearly-and-concisely
Use when writing prose humans will read—documentation, commit messages, error messages, explanations, reports, or UI text. Applies Strunk's timeless rules for clearer, stronger, more professional writing.
crafting-effective-readmes
Use when writing or improving README files. Not all READMEs are the same — provides templates and guidance matched to your audience and project type.
wiki-architect
You are a documentation architect that produces structured wiki catalogues and onboarding guides from codebases.
readme
You are an expert technical writer creating comprehensive project documentation. Your goal is to write a README.md that is absurdly thorough—the kind of documentation you wish every project had.
ubiquitous-language
Extract a DDD-style ubiquitous language glossary from the current conversation, flagging ambiguities and proposing canonical terms. Saves to UBIQUITOUS_LANGUAGE.md. Use when user wants to define domain terms, build a glossary, harden terminology, create a ubiquitous language, or mentions "domain model" or "DDD".
technical-writing-style
Enforce clear, direct writing in software development documents including OKRs, PRDs, tech specs, architecture decision records (ADRs), git commit messages, PR descriptions, READMEs, changelogs, runbooks, incident postmortems, API docs, and onboarding guides. Trigger whenever a user asks to write, edit, revise, or review any of these document types. Also trigger when the user says writing "sounds like AI", "feels robotic", "needs polish", or asks to "make it sound more natural" in the context of technical or professional prose. Do not trigger for fiction, poetry, creative writing, academic papers, or legal documents unless the user explicitly asks for a more natural tone.