Architecture & CQRS
0. Project context
Resolve once per session, from the working directory: the solution (*.sln / *.slnx, else
*.csproj — ask if several match) and its projects by role: <Api>, <Application>, <Core>,
<Infrastructure>, <Tests>. Those placeholders mean the real project names; paths below are relative
to the solution root. Take product names from the repo — never invent one. If the solution is not
layered this way, say so and ask before imposing this structure.
1. Clean Architecture — Layer Rules
The solution is structured into four immutable layers. Dependency flow is strictly inward:
Web → Application → Core ← Infrastructure
| Layer | Responsibility | Forbidden |
|---|---|---|
| Core | Entities, Enums, Interfaces (IRepository<T>, IUnitOfWork, service contracts) | References to any other layer |
| Application | MediatR Commands/Queries/Handlers, FluentValidation Validators, DTOs, Mapster config | Direct DB access, HTTP, Refit |
| Infrastructure | EF Core DbContext, Repositories, UoW, Refit clients, DelegatingHandlers, JWT | MediatR, Application DTOs |
| Web | Controllers, Program.cs, Middleware, OpenAPI/Swagger config | Business logic of any kind |
Violations that must never occur:
- A Controller containing any logic beyond
await _mediator.Send(command). - An Application handler
usingany Infrastructure namespace. - A Core entity referencing Application or Infrastructure types.
2. CQRS with MediatR
Command / Query Naming
Features/
<BoundedContext>/
Commands/
<ActionName>Command/
<ActionName>Command.cs ← IRequest<TResult>
<ActionName>CommandValidator.cs ← AbstractValidator<TCommand>
<ActionName>CommandHandler.cs ← IRequestHandler<TCommand, TResult>
Queries/
<QueryName>Query/
<QueryName>Query.cs
<QueryName>QueryHandler.cs
DTOs/
<Entity>Response.cs
Handler Rules
- All business logic must live inside the Handler's
Handle()method. - Handlers receive dependencies via constructor injection only.
- Handlers must inject
IUnitOfWork(notAppDbContextdirectly). - Handlers must inject Core service interfaces (e.g.,
IPaymentGatewayService), never Infrastructure implementations. - Return types are always a DTO/Result record — never a raw Entity.
Controller Rules
// ✅ CORRECT — thin dispatcher
[HttpPost]
public async Task<IActionResult> Create([FromBody] CreateOrderCommand cmd, CancellationToken ct)
=> Ok(await _mediator.Send(cmd, ct));
// ❌ FORBIDDEN — logic in controller
[HttpPost]
public async Task<IActionResult> Create([FromBody] CreateOrderRequest req)
{
var order = new Order { ... }; // ← business logic belongs in handler
...
}
3. MediatR Pipeline Behaviors
Two required behaviors must be registered in order in Application/DependencyInjection.cs:
LoggingBehavior<TRequest, TResponse>— logs request type, execution time.ValidationBehavior<TRequest, TResponse>— runs FluentValidation; throwsValidationExceptionbefore the handler is reached.
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
RequestHandlerDelegate<TResponse> is parameterless in MediatR 12 — call as next(), not next(cancellationToken).
4. Mapping (Mapster)
- All object transformations use
IMapper.Adapt<TDestination>(). - Mappings are configured in
Application/Mapping/MappingConfig.csusingTypeAdapterConfig. - Handlers inject
IMapper— never callTypeAdapter.Adapt<>()directly.
5. Modules (Microservice Readiness)
Applies when the backend is a modular monolith — one deployable, one database, a module per bounded
context (a database schema plus the Features/* folders that own its tables). Within a module, code calls
freely. Between modules: call a port in Core/Interfaces/<Module>/ or publish a MediatR notification —
never send another module's command, load its entities, walk a navigation into its tables, or create a cycle.
Read reference/modular-monolith.md before any change that crosses a module boundary, adds a feature folder, or adds a port. Skip it for a single-module backend.
6. Security
- All endpoints require
[Authorize]by default. Opt-out with[AllowAnonymous]only for auth endpoints. - JWT claims are accessed exclusively via
ICurrentUserService— never viaHttpContext.Userin handlers. - Brute-force protection (lockout) lives in the login handler — not in the controller or middleware.
Per-resource authorization — the handler's job, not the attribute's
[Authorize(Roles="...")] proves the caller has a role. It does not prove the caller owns the
row whose id they just sent. Every handler that accepts an entity id from the request must
verify ownership against ICurrentUserService.UserId before reading or writing:
// ❌ BOLA/IDOR — any authenticated caller can read any row by guessing/enumerating the id
var record = await _unitOfWork.Repository<Order>().GetByIdAsync(request.Id, ct);
// ✅ ownership is part of the lookup predicate
var record = await _unitOfWork.Repository<Order>().SingleOrDefaultAsync(
b => b.Id == request.Id && b.OwnerUserId == _currentUser.UserId, ct)
?? throw new NotFoundException();
Rules:
- Scope by owner in the query predicate, not with an
ifafter loading — a post-load check that someone later refactors away fails open. - Return
404, not403, for a resource the caller may not see.403confirms the row exists. - Each role's scope is its own data: a customer sees their own orders and payments, a manager the
records of the organization they manage. Only
Adminmay cross that boundary, and an admin cross-account read writes an audit-log entry. - Never take
userId,ownerId, ororganizationIdfrom the request body or query string as the identity to act on — derive it fromICurrentUserService. A request-supplied id is a target to authorize, never a claim of who you are. - Signed-link confirmation endpoints are
[AllowAnonymous]: the token is the authorization. It must be single-use, expiring, high-entropy, and compared in constant time — and it authorizes exactly the one record it was minted for. - Never bind a request DTO straight onto an entity. Role, status, price, and eligibility fields must never be settable from the wire (over-posting → privilege escalation).
7. Error Handling
Throw project-owned exceptions (NotFoundException 404, ForbiddenException 403, ConflictException 409;
FluentValidation ValidationException 422) and let a global handler map them to ProblemDetails. Never
throw or map BCL types such as InvalidOperationException or KeyNotFoundException — the framework raises
those for real defects, which must surface as a logged 500. No catch-all in handlers.
The full failure path — exception base and code vocabulary, handler implementation, wire shape, log
levels, persistence and webhook failures — is [[error-handling-dotnet]].
Checklist Before Completing Work
- Business logic lives in Application handlers, not controllers or Infrastructure
- Layer dependencies point inward; Core has zero outward references
- Command/query follows CQRS; controller only dispatches via MediatR
- Handler injects
IUnitOfWorkand Core interfaces — notAppDbContextor Refit - Changes respect module boundaries: cross-module calls go through a Core port or an event, the accepted-coupling baseline did not grow, architecture tests green
- A new feature folder is assigned a module; a new table lives in its module schema
- Pipeline behaviors and Mapster conventions followed where applicable