# Architecture Documentation > Detailed architecture documentation for the .NET 10 Microservice Template. ## Architecture Overview ```mermaid graph TB subgraph "API Layer" C[Controllers] CMD[Commands] Q[Queries] B[Behaviors] V[Validations] end subgraph "Domain Layer" AR[Aggregate Roots] E[Entities] VO[Value Objects] DE[Domain Events] DX[Domain Exceptions] end subgraph "Infrastructure Layer" DB[(PostgreSQL)] R[Repositories] CTX[DbContext] ID[Idempotency] end C --> CMD C --> Q CMD --> B --> V CMD --> AR Q --> R R --> CTX --> DB AR --> DE R --> AR style C fill:#4a90d9,stroke:#2d5986,color:#fff style AR fill:#50c878,stroke:#2d8659,color:#fff style DB fill:#ff6b6b,stroke:#c0392b,color:#fff ``` ## Layer Responsibilities ### 1. Domain Layer (MyService.Domain) The heart of the application containing pure business logic. This layer: - Has **ZERO** external dependencies (except MediatR.Contracts for events) - Contains only POCO classes - Implements DDD tactical patterns #### Components | Component | Purpose | |-----------|---------| | **SeedWork** | Base classes: Entity, ValueObject, Enumeration, IAggregateRoot | | **AggregatesModel** | Aggregate roots with their entities and value objects | | **Events** | Domain events for cross-aggregate communication | | **Exceptions** | Domain-specific exceptions for business rule violations | ### 2. Infrastructure Layer (MyService.Infrastructure) Technical implementations and external concerns: - Database access (EF Core) - Repository implementations - External service integrations ### 3. API Layer (MyService.API) Application entry point and CQRS implementation: - Controllers for HTTP handling - Commands for write operations - Queries for read operations - MediatR behaviors for cross-cutting concerns ## CQRS Flow ```mermaid sequenceDiagram participant Client participant Controller participant MediatR participant LoggingBehavior participant ValidatorBehavior participant TransactionBehavior participant CommandHandler participant Repository participant DbContext Client->>Controller: HTTP Request Controller->>MediatR: Send(Command) MediatR->>LoggingBehavior: Handle LoggingBehavior->>ValidatorBehavior: Next() ValidatorBehavior->>TransactionBehavior: Next() TransactionBehavior->>CommandHandler: Next() CommandHandler->>Repository: Add/Update/Delete Repository->>DbContext: SaveEntitiesAsync() DbContext-->>Repository: Success Repository-->>CommandHandler: Result CommandHandler-->>Controller: Response Controller-->>Client: HTTP Response ``` ## Domain Events ```mermaid graph LR AR[Aggregate Root] -->|Raises| DE[Domain Event] DE -->|Dispatched by| CTX[DbContext] CTX -->|Publishes to| M[MediatR] M -->|Handled by| H1[Handler 1] M -->|Handled by| H2[Handler 2] style AR fill:#50c878,stroke:#2d8659,color:#fff style DE fill:#f39c12,stroke:#d68910,color:#fff style M fill:#9b59b6,stroke:#7d3c98,color:#fff ``` ## Database Schema ### Sample Aggregate ```mermaid erDiagram samples { uuid id PK varchar(200) name varchar(1000) description int status_id FK timestamp created_at timestamp updated_at } sample_statuses { int id PK varchar(50) name } samples ||--o{ sample_statuses : has ``` ## MediatR Pipeline ``` Request → LoggingBehavior → ValidatorBehavior → TransactionBehavior → Handler → Response │ │ │ ▼ ▼ ▼ Log start/end Validate Begin/Commit + timing with Transaction FluentValidation ``` ### Behavior Order 1. **LoggingBehavior** - Logs request handling with timing 2. **ValidatorBehavior** - Validates request using FluentValidation 3. **TransactionBehavior** - Wraps command handlers in database transactions ## Error Handling ### Exception Hierarchy ``` Exception └── DomainException └── SampleDomainException ``` ### Problem Details (RFC 7807) All errors are returned in Problem Details format: ```json { "type": "https://tools.ietf.org/html/rfc7807", "title": "Validation Error", "status": 400, "detail": "One or more validation errors occurred.", "errors": { "Name": ["Name is required"] } } ``` ## Health Checks ```mermaid graph TD HC[Health Check Endpoint] HC --> |/health/live| L[Liveness] HC --> |/health/ready| R[Readiness] HC --> |/health| F[Full Status] R --> PG[(PostgreSQL)] R --> RD[(Redis)] style HC fill:#3498db,stroke:#2980b9,color:#fff style L fill:#2ecc71,stroke:#27ae60,color:#fff style R fill:#f39c12,stroke:#d68910,color:#fff ``` ## Deployment Architecture ### Docker Compose (Local) ```yaml services: myservice-api: build: . ports: ["5000:8080"] depends_on: - postgres - redis postgres: image: postgres:16-alpine redis: image: redis:7-alpine ``` ### Kubernetes (Production) ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: myservice-api spec: replicas: 3 template: spec: containers: - name: api image: myservice:latest ports: - containerPort: 8080 livenessProbe: httpGet: path: /health/live port: 8080 readinessProbe: httpGet: path: /health/ready port: 8080 ``` ## Security Considerations 1. **Authentication**: JWT Bearer token (configure in production) 2. **Authorization**: Role-based access control 3. **Input Validation**: FluentValidation on all requests 4. **SQL Injection**: EF Core parameterized queries 5. **Secrets**: Environment variables, never in code ## Performance Optimization 1. **Connection Pooling**: EF Core with Npgsql connection resilience 2. **Async/Await**: All I/O operations are async 3. **Response Caching**: Add caching headers for queries 4. **Database Indexes**: Configure in EntityConfigurations ## References - [eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers) - [.NET Microservices Architecture Guide](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/) - [Domain-Driven Design](https://martinfowler.com/bliki/DomainDrivenDesign.html) - [CQRS Pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/cqrs)