Design and structure .NET back-end solutions — modular monolith versus separate services, solution and assembly boundaries, vertical slices versus a layered domain, aggregates and data ownership, multi-tenancy isolation, CQRS and mediator trade-offs, hosting model (container, serverless, Aspire), where cross-cutting concerns live, and the ADR that records the decision.
When agents use itUse this whenever the user starts a new .NET solution, lays out a *.sln or *.slnx with several *.csproj projects, asks "how should I structure this .NET service", debates microservices versus a modular monolith, decides where a module's DbContext and schema belong, wants one module to read another module's data, designs a tenant isolation model, weighs MediatR, MassTransit or AutoMapper licensing, or plans Aspire and container deployment. Also use it when a .NET system needs an architecture decision record.
Install
Copilot (VS Code, Visual Studio, Copilot CLI and github.com) reads skills from the repository — commit them so the whole team gets them.
npx skills add AGCO-Global/org-skills --skill dotnet-architecture -a github-copilot
# or with the org installer (adds .github/skills/dotnet-architecture):
npx -y github:AGCO-Global/org-skills add skill dotnet-architecture
Uses the open skills CLI. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, OpenCode, Windsurf and 60+ others — it asks which agent to install into.
Installs the backend-dotnet-skills plugin, which bundles all Backend / .NET skills and keeps them updated.
/plugin marketplace add AGCO-Global/org-skills
/plugin install backend-dotnet-skills@org-skills
# or just this skill, in this repository:
npx skills add AGCO-Global/org-skills --skill dotnet-architecture -a claude-code
Use Download .zip above, then upload it under Customize → Skills → Upload skill. Team and Enterprise admins can sync this repo as a plugin marketplace instead.
Installs into .agents/skills/, which Codex reads.
npx skills add AGCO-Global/org-skills --skill dotnet-architecture -a codex
Installs into Cursor's skills folder.
npx skills add AGCO-Global/org-skills --skill dotnet-architecture -a cursor
Installs into Gemini CLI's skills folder.
npx skills add AGCO-Global/org-skills --skill dotnet-architecture -a gemini-cli
Nothing to install. Press Download .zip above, unzip it, and drop the dotnet-architecture folder into your tool's skills folder — .claude/skills/, .github/skills/, .cursor/skills/ or .agents/skills/. Step-by-step, per tool: How to use it. For any other tool with rules or custom prompts, Copy SKILL.md and paste it in — it is plain Markdown.
The npx commands need Node.js 20+ and use your normal git sign-in to GitHub, so they work while the repository is private. Without Node.js, see the No Node.js tab — a skill is a folder of Markdown, so copying it in works just as well.
Think like the engineer who still owns this system in three years: optimise for changeability and boundaries you can enforce in CI, not for the number of patterns applied. Every recommendation names the force that would flip it, and every boundary you draw comes with the mechanism that keeps it drawn.
1. Decide first
Question
Default
Change when
One deployable or many?
Modular monolith: one host, modules with enforced boundaries
Independent scaling or release cadence is proven necessary, teams block each other, or isolation is a compliance requirement
Rich invariants → a real Domain project in that module only
Module-to-module call
In-process call through the other module's *.Contracts interface
Slow work, side effects that must not block the request, or planned extraction → events (messaging-patterns)
Data ownership
Schema per module, one database server
A module is extracted — its schema travels with it
Multi-tenancy
Shared schema + TenantId + EF global query filter
Regulatory or noisy-neighbour pressure → schema or database per tenant (references/multi-tenancy.md)
Hosting
Long-running container behind a load balancer
Spiky, event-driven, sub-second work with no warm-up need → Azure Functions isolated worker (references/hosting-models.md)
Shared cache
HybridCache inside the module that owns the data
Never a cache shared between modules — it re-creates the coupling you removed
A well-bounded modular monolith is the cheapest path to services later. A distributed monolith is the most expensive path to anything.
2. Solution layout
src/
Host/ ← composition root: Program.cs, config, auth, OTel, module registration
Modules/Orders/
Orders.Contracts/ ← public DTOs, integration events, the module's interface
Orders/ ← internal: slices, domain, EF DbContext, migrations
Modules/Billing/...
BuildingBlocks/ ← small and stable: result types, outbox, messaging abstractions
tests/
Directory.Build.props ← nullable, warnings-as-errors, analyzers
Directory.Packages.props ← central package management
Each module exposes one registration method and one endpoint method, so the host stays a list of modules rather than a list of endpoints:
public static class OrdersModule
{
public static IServiceCollection AddOrders(this IServiceCollection services, IConfiguration config) => services;
public static IEndpointRouteBuilder MapOrders(this IEndpointRouteBuilder routes) => routes;
}
A project boundary is a compile-time boundary — create one where it enforces something. Ten projects for a twenty-endpoint service is ceremony. BuildingBlocks that references a module is in the wrong place.
3. Guardrails: make each decision enforceable
A boundary that only lives in a document is already broken. Pair every decision with a mechanism:
Decision
Enforced by
Modules depend only on *.Contracts
Architecture test over assembly references (references/architecture-tests.md)
Domain does not reference EF Core or ASP.NET Core
Architecture test on namespace dependencies
Implementation types are internal
InternalsVisibleTo for tests only; architecture test for public types outside Contracts
No cross-module foreign key
EF model test walking Model.GetEntityTypes() foreign keys
Every state change that publishes has an outbox row
Integration test on the handler; code review checklist
Warnings, nullability, package audit
Directory.Build.props + dotnet build /warnaserror in CI
Public contract unchanged by accident
OpenAPI document diff in CI (api-design)
4. Domain modelling without ceremony
Aggregates own invariants and are the unit of consistency: one transaction changes one aggregate; cross-aggregate rules become eventually consistent through events.
Value objects as record or readonly record struct (Money, EmailAddress) with validation in the factory — this is what kills primitive obsession.
Behaviour methods (order.Cancel(reason)) with private setters; EF Core maps backing fields without public setters.
Reference other aggregates by id. A navigation property across a module boundary is a cross-module join waiting to happen.
Skip tactical DDD in CRUD modules. An anaemic model is correct when there are no invariants to protect.
5. CQRS, mediators and library licences
Separate read and write models: writes go through aggregates, reads are AsNoTracking projections (or Dapper) straight to DTOs. That is the part that pays.
An in-process mediator is optional. It earns its place when one pipeline (validation, logging, transaction, idempotency) must wrap many handlers. A handler class injected into the endpoint is clearer when it does not. Never call a handler from a handler.
Check licences before adopting: MediatR ≥ 13 and AutoMapper ≥ 15 became commercial on 2025-07-02, as did MassTransit v9; earlier pinned majors stay under their original open-source licence. Prefer endpoint filters, source-generated mapping or hand-written mapping over a paid dependency for a thin need.
6. Data ownership and migrations
One DbContext per module with HasDefaultSchema("orders"). No cross-module joins, foreign keys or navigations. To read another module's data: call its contract, or keep a local read model fed by its events.
Migrations belong to the module that owns the schema and deploy with it. Ordering between modules is a design smell — if module B's migration must run before module A's, they share a table.
Reporting that must join everything goes to a separate read store, never into a module.
Zero-downtime DDL, backfills and expand/contract: database-migrations.
7. Messaging and API contracts
Both are owned elsewhere in this catalog; do not restate them in an ADR.
Asynchronous integration — outbox, idempotent consumers, event versioning, DLQ, sagas: messaging-patterns. The .NET-specific part is the library: MassTransit or NServiceBus (outbox, retries, saga persistence built in) over a raw broker SDK, unless you need broker-level features.
HTTP contracts — resources, status codes, pagination, idempotency keys, versioning and deprecation: api-design. In .NET, version with Asp.Versioning.Http (minimal APIs) or Asp.Versioning.Mvc; a URL segment (/v1/) is the most operable default.
8. Where cross-cutting concerns live
Concern
Placement
Authentication
Host, validating against the IdP's JWKS. With many internal services behind one entry point, validate at the gateway and forward a signed internal token
Authorization policies
Host declares them; modules require them on their endpoint groups
Authorization rules about a module's resources
Inside the module — the host cannot know who owns order 42
Validation, logging, transactions
One mechanism per solution: endpoint filters, middleware or pipeline behaviours
Errors
ProblemDetails + IExceptionHandler in the host (dotnet-development)
Put a BFF in front only when a client needs a genuinely different shape (mobile payload trimming, session cookies for a browser SPA). A BFF that forwards one-to-one is a hop that costs latency and buys nothing.
9. Deliverable format
## Context and forces load, team size, domain complexity, compliance (ask if unknown)
## Recommendation deployment shape, module map, solution tree
## ADR(s) Title / Status / Context / Decision / Consequences (+ and −) / Alternatives
## Guardrails each decision → the test, analyzer or CI check that enforces it (§3)
## Migration path small, independently shippable steps from today's state
Checklist
The recommendation names the condition that would flip it.
Every module boundary has an enforcing test or analyzer, not just a convention.
Each module owns its schema; no cross-module foreign key or join.
The tenancy model is stated, and the query filter or connection strategy that implements it.
Asynchronous integration links to messaging-patterns; HTTP contracts link to api-design.
Library licence thresholds checked before recommending MediatR, AutoMapper or MassTransit.
Hosting model justified by the workload shape, not by familiarity.
An ADR exists with alternatives and negative consequences written down.
The migration path is a sequence of shippable steps, not a rewrite.
Anti-patterns
Microservices for one team's greenfield product → modular monolith with enforced boundaries; extract when a named force appears.
Shared database between "services" → that is a distributed monolith; either merge them or split the schema.
Common/Shared/Utils project everyone edits → per-module code, or a small stable BuildingBlocks that depends on nothing.
Generic IRepository<T> over EF Core → the DbContext is already a unit of work; use query classes for reads.
Cross-module navigation property → reference by id; read through the owner's contract or an event-fed read model.
Boundaries documented but not tested → an architecture test per rule (§3).
Tenant filtering written by hand in every query → global query filter plus a test that fails when an entity lacks one.
Go deeper
references/architecture-tests.md — NetArchTest and ArchUnitNET rules for module and layer dependencies, the EF cross-schema foreign-key test, and how to fail CI on a violation.
references/multi-tenancy.md — isolation models compared, EF Core 10 named query filters, tenant resolution and DbContext pooling caveats, per-tenant migrations.
references/hosting-models.md — container versus Azure Functions isolated worker, Aspire 13 app host and service defaults, what Aspire does and does not do at deploy time.
Sibling skills: dotnet-development for the code, dotnet-testing for tests, dotnet-performance for symptoms, messaging-patterns, api-design, database-migrations, service-operability, backend-code-review for reviews.
---
name: dotnet-architecture
description: >
Design and structure .NET back-end solutions — modular monolith versus separate services, solution and assembly boundaries, vertical slices versus a layered domain, aggregates and data ownership, multi-tenancy isolation, CQRS and mediator trade-offs, hosting model (container, serverless, Aspire), where cross-cutting concerns live, and the ADR that records the decision. Use this whenever the user starts a new .NET solution, lays out a *.sln or *.slnx with several *.csproj projects, asks "how should I structure this .NET service", debates microservices versus a modular monolith, decides where a module's DbContext and schema belong, wants one module to read another module's data, designs a tenant isolation model, weighs MediatR, MassTransit or AutoMapper licensing, or plans Aspire and container deployment. Also use it when a .NET system needs an architecture decision record.
metadata:
technology: .NET
type: architecture
---
# .NET Architecture
> **Targets:** .NET 10 LTS, ASP.NET Core 10, EF Core 10, Aspire 13 (.NET 8 LTS noted where different) · **Verified:** 2026-09 against https://learn.microsoft.com/en-us/dotnet/architecture/modern-web-apps-azure/
Think like the engineer who still owns this system in three years: optimise for changeability and boundaries you can enforce in CI, not for the number of patterns applied. Every recommendation names the force that would flip it, and every boundary you draw comes with the mechanism that keeps it drawn.
## 1. Decide first
| Question | Default | Change when |
|---|---|---|
| One deployable or many? | **Modular monolith**: one host, modules with enforced boundaries | Independent scaling or release cadence is *proven* necessary, teams block each other, or isolation is a compliance requirement |
| Inside a module | **Vertical slices** (`Orders/PlaceOrder/{Endpoint,Handler,Validator}`) | Rich invariants → a real `Domain` project in that module only |
| Module-to-module call | In-process call through the other module's `*.Contracts` interface | Slow work, side effects that must not block the request, or planned extraction → events (`messaging-patterns`) |
| Data ownership | **Schema per module**, one database server | A module is extracted — its schema travels with it |
| Multi-tenancy | Shared schema + `TenantId` + EF global query filter | Regulatory or noisy-neighbour pressure → schema or database per tenant (`references/multi-tenancy.md`) |
| Hosting | Long-running container behind a load balancer | Spiky, event-driven, sub-second work with no warm-up need → Azure Functions isolated worker (`references/hosting-models.md`) |
| Shared cache | `HybridCache` inside the module that owns the data | Never a cache shared between modules — it re-creates the coupling you removed |
A well-bounded modular monolith is the cheapest path to services later. A distributed monolith is the most expensive path to anything.
## 2. Solution layout
```
src/
Host/ ← composition root: Program.cs, config, auth, OTel, module registration
Modules/Orders/
Orders.Contracts/ ← public DTOs, integration events, the module's interface
Orders/ ← internal: slices, domain, EF DbContext, migrations
Modules/Billing/...
BuildingBlocks/ ← small and stable: result types, outbox, messaging abstractions
tests/
Directory.Build.props ← nullable, warnings-as-errors, analyzers
Directory.Packages.props ← central package management
```
Each module exposes one registration method and one endpoint method, so the host stays a list of modules rather than a list of endpoints:
```csharp
public static class OrdersModule
{
public static IServiceCollection AddOrders(this IServiceCollection services, IConfiguration config) => services;
public static IEndpointRouteBuilder MapOrders(this IEndpointRouteBuilder routes) => routes;
}
```
A project boundary is a compile-time boundary — create one where it enforces something. Ten projects for a twenty-endpoint service is ceremony. `BuildingBlocks` that references a module is in the wrong place.
## 3. Guardrails: make each decision enforceable
A boundary that only lives in a document is already broken. Pair every decision with a mechanism:
| Decision | Enforced by |
|---|---|
| Modules depend only on `*.Contracts` | Architecture test over assembly references (`references/architecture-tests.md`) |
| Domain does not reference EF Core or ASP.NET Core | Architecture test on namespace dependencies |
| Implementation types are `internal` | `InternalsVisibleTo` for tests only; architecture test for public types outside `Contracts` |
| No cross-module foreign key | EF model test walking `Model.GetEntityTypes()` foreign keys |
| Every state change that publishes has an outbox row | Integration test on the handler; code review checklist |
| Warnings, nullability, package audit | `Directory.Build.props` + `dotnet build /warnaserror` in CI |
| Public contract unchanged by accident | OpenAPI document diff in CI (`api-design`) |
## 4. Domain modelling without ceremony
- **Aggregates** own invariants and are the unit of consistency: one transaction changes one aggregate; cross-aggregate rules become eventually consistent through events.
- **Value objects** as `record` or `readonly record struct` (`Money`, `EmailAddress`) with validation in the factory — this is what kills primitive obsession.
- Behaviour methods (`order.Cancel(reason)`) with private setters; EF Core maps backing fields without public setters.
- Reference other aggregates by **id**. A navigation property across a module boundary is a cross-module join waiting to happen.
- Skip tactical DDD in CRUD modules. An anaemic model is correct when there are no invariants to protect.
## 5. CQRS, mediators and library licences
Separate read and write models: writes go through aggregates, reads are `AsNoTracking` projections (or Dapper) straight to DTOs. That is the part that pays.
An in-process mediator is **optional**. It earns its place when one pipeline (validation, logging, transaction, idempotency) must wrap many handlers. A handler class injected into the endpoint is clearer when it does not. Never call a handler from a handler.
Check licences before adopting: **MediatR ≥ 13** and **AutoMapper ≥ 15** became commercial on 2025-07-02, as did **MassTransit v9**; earlier pinned majors stay under their original open-source licence. Prefer endpoint filters, source-generated mapping or hand-written mapping over a paid dependency for a thin need.
## 6. Data ownership and migrations
- One `DbContext` per module with `HasDefaultSchema("orders")`. No cross-module joins, foreign keys or navigations. To read another module's data: call its contract, or keep a local read model fed by its events.
- Migrations belong to the module that owns the schema and deploy with it. Ordering between modules is a design smell — if module B's migration must run before module A's, they share a table.
- Reporting that must join everything goes to a separate read store, never into a module.
- Zero-downtime DDL, backfills and expand/contract: `database-migrations`.
## 7. Messaging and API contracts
Both are owned elsewhere in this catalog; do not restate them in an ADR.
- **Asynchronous integration** — outbox, idempotent consumers, event versioning, DLQ, sagas: `messaging-patterns`. The .NET-specific part is the library: **MassTransit** or **NServiceBus** (outbox, retries, saga persistence built in) over a raw broker SDK, unless you need broker-level features.
- **HTTP contracts** — resources, status codes, pagination, idempotency keys, versioning and deprecation: `api-design`. In .NET, version with `Asp.Versioning.Http` (minimal APIs) or `Asp.Versioning.Mvc`; a URL segment (`/v1/`) is the most operable default.
## 8. Where cross-cutting concerns live
| Concern | Placement |
|---|---|
| Authentication | Host, validating against the IdP's JWKS. With many internal services behind one entry point, validate at the gateway and forward a signed internal token |
| Authorization policies | Host declares them; modules require them on their endpoint groups |
| Authorization rules about *a module's* resources | Inside the module — the host cannot know who owns order 42 |
| Validation, logging, transactions | One mechanism per solution: endpoint filters, middleware or pipeline behaviours |
| Errors | ProblemDetails + `IExceptionHandler` in the host (`dotnet-development`) |
| Rate limiting, CORS, output caching | Built-in middleware in the host |
| Health, shutdown, OpenTelemetry, container image | `service-operability` |
| Time, ids, current user, tenant | Injected abstractions (`TimeProvider`, `ICurrentUser`, `ITenantContext`) |
Put a BFF in front only when a client needs a genuinely different shape (mobile payload trimming, session cookies for a browser SPA). A BFF that forwards one-to-one is a hop that costs latency and buys nothing.
## 9. Deliverable format
```
## Context and forces load, team size, domain complexity, compliance (ask if unknown)
## Recommendation deployment shape, module map, solution tree
## ADR(s) Title / Status / Context / Decision / Consequences (+ and −) / Alternatives
## Guardrails each decision → the test, analyzer or CI check that enforces it (§3)
## Migration path small, independently shippable steps from today's state
```
## Checklist
- [ ] The recommendation names the condition that would flip it.
- [ ] Every module boundary has an enforcing test or analyzer, not just a convention.
- [ ] Each module owns its schema; no cross-module foreign key or join.
- [ ] The tenancy model is stated, and the query filter or connection strategy that implements it.
- [ ] Asynchronous integration links to `messaging-patterns`; HTTP contracts link to `api-design`.
- [ ] Library licence thresholds checked before recommending MediatR, AutoMapper or MassTransit.
- [ ] Hosting model justified by the workload shape, not by familiarity.
- [ ] An ADR exists with alternatives and negative consequences written down.
- [ ] The migration path is a sequence of shippable steps, not a rewrite.
## Anti-patterns
- **Microservices for one team's greenfield product** → modular monolith with enforced boundaries; extract when a named force appears.
- **Shared database between "services"** → that is a distributed monolith; either merge them or split the schema.
- **`Common`/`Shared`/`Utils` project everyone edits** → per-module code, or a small stable `BuildingBlocks` that depends on nothing.
- **Generic `IRepository<T>` over EF Core** → the `DbContext` is already a unit of work; use query classes for reads.
- **Cross-module navigation property** → reference by id; read through the owner's contract or an event-fed read model.
- **Boundaries documented but not tested** → an architecture test per rule (§3).
- **Tenant filtering written by hand in every query** → global query filter plus a test that fails when an entity lacks one.
## Go deeper
- `references/architecture-tests.md` — NetArchTest and ArchUnitNET rules for module and layer dependencies, the EF cross-schema foreign-key test, and how to fail CI on a violation.
- `references/multi-tenancy.md` — isolation models compared, EF Core 10 named query filters, tenant resolution and `DbContext` pooling caveats, per-tenant migrations.
- `references/hosting-models.md` — container versus Azure Functions isolated worker, Aspire 13 app host and service defaults, what Aspire does and does not do at deploy time.
- Sibling skills: `dotnet-development` for the code, `dotnet-testing` for tests, `dotnet-performance` for symptoms, `messaging-patterns`, `api-design`, `database-migrations`, `service-operability`, `backend-code-review` for reviews.