The .NET realization of `clean-architecture`: how a .NET service is packaged and composed. Use when creating or reviewing a .NET solution's structure, adding a module (bounded context) or a project, adding a use case (an Application service), an endpoint or a bus handler, securing an HTTP API or a webhook, deciding what is public or internal, wiring the host's ProgramBuilder/ProgramApplication, or placing contracts, read models and shared kernels. It encodes: one project per module with its l...
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Clean Architecture Dotnet?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/jorgecostamacia-clean-architecture-dotnet-code-harness)
---
name: clean-architecture-dotnet
description: >-
The .NET realization of `clean-architecture`: how a .NET service is
packaged and composed. Use when creating or reviewing a .NET solution's
structure, adding a module (bounded context) or a project, adding a use
case (an Application service), an endpoint or a bus handler, securing an
HTTP API or a webhook, deciding what is public or internal, wiring the
host's ProgramBuilder/ProgramApplication, or placing contracts, read
models and shared kernels. It encodes: one project per module with its
layer folders, internal by default with one public *Context per module,
the Add<Module>Context / Map<Module>…Context composition, use-case
services that take primitives and return what the adapter sends, the host
as composition only, the API's exposure stated in AGENTS.md and what it
adds (authentication, CORS, HSTS, rate limits), a 500 without the
exception's detail, the published pieces in repositories of their own, the
internal Shared kernels, the reserved segments, and the composition test.
---
# Clean architecture in .NET
The .NET *how* of `clean-architecture` (load it for the *why*). It shows how a service maps its bounded contexts and layers onto projects, and how the host composes them.
## Projects
```text
src/
├─ <Service>/ the host: Program.cs, ProgramBuilder.cs, ProgramApplication.cs — no logic of its own
├─ <Service>.<Module>/ one project per bounded context
│ ├─ Domain/ aggregates, value objects, validators, typed exceptions
│ ├─ Application/ the use-case services + <Module>ApplicationContext
│ ├─ Infrastructure/ <Module>InfrastructureContext, the DbContext, external clients
│ ├─ Presentation/ the driving adapters (bus handlers, endpoints) + <Module>…PresentationContext
│ └─ <Module>Context.cs the module's only public type
└─ <Service>.Shared.<X>/ a shared kernel, one per concern — internal, never packed
test/
└─ <Service>.<Module>.Tests/ one suite per project (an API with endpoint-only modules: one suite for the host)
```
- **The layers are folders inside the module's project**, not projects of their own. Review and the namespaces hold the dependency rule of `clean-architecture`. Domain imports nothing from the other folders. Application imports only Domain, the module's contracts package, whose events it builds and returns (see `ddd-dotnet`), and its aggregate's DbContext in Infrastructure, the accepted coupling of `clean-architecture`. Infrastructure and Presentation import only inward and never each other. A module therefore stays one unit to add, move or delete. A module holds **the layers it needs**: a worker's module has all four. A webhook module that only turns a request into an event has only `Presentation/`; it still authenticates its sender and validates the request (see *HTTP endpoints*). A module's `.csproj` references contracts packages — its own and those it consumes — and the service's shared kernels it uses, never another module's project.
- **The host references every module project** and nothing else of theirs but their `<Module>Context`.
- The module takes its name from the ubiquitous language (`Pedidos`, `Expedientes`), and so does its aggregate. So `Pedidos` is both the namespace segment and the type. Inside the module, where the namespace would shadow the type, the code reaches it as `Domain.Pedidos`. The code reaches the module's contracts context as `Contracts.Pedidos.PedidosContext`, since the runtime's own `PedidosContext` hides it. Both forms are the convention, not a smell — in `src/`; the `using PedidosAggregate = …` alias is the tests' idiom (see `testing-dotnet`), not production's. `Contracts`, `Query` and `Shared` are **reserved segments**: no module may take one as its name.
## Internal by default
Everything inside a module is `internal`: aggregates, value objects, services (`internal sealed`), handlers, the DbContext, the layer contexts. The one public type is the static `<Module>Context`. The module's suite reaches the rest through `<InternalsVisibleTo Include="<Service>.<Module>.Tests" />` in the module's `.csproj` — no type becomes public for a test's sake.
## The *Context composition pattern
Each module composes itself through static extension methods, layer by layer:
```csharp
public static class PedidosContext
{
public static IServiceCollection AddPedidosContext(this IServiceCollection services, IConfiguration configuration)
{
services
.AddPedidosInfrastructureContext(configuration)
.AddPedidosApplicationContext();
return services;
}
public static ConsumerConfigurator MapPedidosBusContext(this ConsumerConfigurator consumer)
{
consumer
.MapPedidosBusPresentationContext();
return consumer;
}
}
```
- **`Add<Module>Context(services, configuration)`** registers the module's services through one `internal static` context per layer that registers something. `<Module>InfrastructureContext` registers the DbContext, the clients and the implementations of the module's ports. `<Module>ApplicationContext` registers the use-case services (`AddScoped<XService>()`, concrete, no interface). A Presentation layer that registers services of its own has its `Add<Module>…PresentationContext`. Domain registers nothing and has no context. A module that reads no configuration takes only `services`. A module that registers nothing returns them unchanged. The method still exists, so the host composes every module the same way.
- **`Map<Module>…Context(...)`** maps the module's driving adapters: `Map<Module>BusContext(consumer)` for its bus handlers, `Map<Module>HttpContext(endpoints)` for its endpoints (a `MapGroup` per module, secured as *HTTP endpoints* says).
- **Read configuration at the place that uses it.** If a required value is missing, the startup fails with a clear message (`GetConnectionString("X") ?? throw new InvalidOperationException("Connection string 'X' is null.")`).
- Each method returns what it received, so the host chains them.
## Application services
A use case is one `internal sealed class <Module><UseCase>Service`, registered scoped, with one public entry point. It takes **primitives** (the values the adapter unpacked from its message or request), plus the correlation id and the consumers. Its last parameter is `CancellationToken cancellationToken = default`. It builds the aggregate through `Domain.<X>.Create(…)`, so every path validates the same way, and it works through the module's `DbContext`. It reads the clock once, in a local `DateTime now = DateTime.UtcNow;` at its start, and **returns** what the adapter then sends or publishes (commands, events, the aggregate). It never receives the transport's object, and never sends or publishes itself.
## The host — composition only
```csharp
// Program.cs — process-wide switches, then build and run
IHost host = Host
.CreateApplicationBuilder(args)
.AddBuilder()
.Build()
.AddApplication();
host.Run();
```
- **`ProgramBuilder.AddBuilder`** does the whole composition: logging, the cross-cutting infrastructure (bus, scheduler, HTTP pipeline services), then every module. The modules come as `.AddPedidosContext(builder.Configuration)` and the `Map…Context` calls, one line per module, in one place.
- **`ProgramApplication.AddApplication`** is the post-build seam. In a worker, it is a pass-through. An API starts from `WebApplication.CreateBuilder(args)` instead, so `AddBuilder` extends `WebApplicationBuilder` and `AddApplication` extends `WebApplication`, where it holds the HTTP middleware pipeline and the endpoint maps. Keep it as the hook either way.
- `Program.cs` holds only what must run before the builder exists (an `AppContext.SetSwitch`).
- No business logic, no use case, no query in the host. An operator's tool (a one-off hosted service) lives there commented out, never registered by default.
## HTTP endpoints — the exposure first
There is no single default. Each service's `AGENTS.md` states its API's exposure: **public** (reached from the internet) or **internal** (a private network, called only by the service's own services), and whether a browser calls it. If it does not say, ask the person before you add an endpoint. The exposure decides what the host adds:
- **Public**: authentication by default. The host sets a fallback policy that requires an authenticated user (`AddAuthorizationBuilder().SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())`). An endpoint is anonymous only with `AllowAnonymous()` and a comment that says why. The public routes have a rate limiter (`AddRateLimiter`, `UseRateLimiter`, `RequireRateLimiting` on the group).
- **Internal**: what the service's architecture says (the private network, service tokens or mTLS).
- **A browser calls it**: CORS with the explicit origins that call it, never any origin. HSTS (`UseHsts`) only when the browser reaches the API over HTTPS. Behind a proxy that terminates TLS, the host reads the forwarded headers first, so it sees the HTTPS scheme (see `logging-dotnet`). An API that no browser calls has no CORS and no HSTS.
Two rules apply to every exposure:
- **A 500 never returns the exception's message or its stack trace.** It returns its status and the ids that find the error in the logs (trace id, request id). The exception goes to the log (see `logging-dotnet`).
- **Input from outside the service's own boundary is validated for shape and size** (see `validation-dotnet`). A public webhook authenticates its sender (a signature or a token) before it reads the content. Between the service's own internal services, a pass-through without a boundary validator is allowed.
## Published and shared pieces
| Piece | Name | Where | Published |
| --- | --- | --- | --- |
| The module's messages — the Published Language | `<Service>.Contracts.<Module>` | its own repository; its own SemVer, apart from the service's, a major when a message breaks or the topics must be created again (the major names the topics) | yes, a NuGet package per module |
| The read model | `<Service>.Query` | its own repository; its own SemVer, a major when a column goes, is renamed or changes its type | yes, one package |
| A shared kernel | `<Service>.Shared.<X>` | `src/` of the service | **never** — internal to the service |
The service consumes its own contracts as a `PackageReference`, like any other consumer.
## The composition test
The host's suite builds the container exactly as production does, against in-memory fake settings, with `ValidateOnBuild` and `ValidateScopes` on (see `testing-dotnet`). It is the test that proves every `Add<Module>Context` registered something that resolves — the safety net for the whole pattern.