6.8 KiB
6.8 KiB
Tài Liệu Kiến Trúc
Tài liệu kiến trúc chi tiết cho Template Microservice .NET 10.
Tổng Quan Kiến Trúc
graph TB
subgraph "Lớp API"
C[Controllers]
CMD[Commands]
Q[Queries]
B[Behaviors]
V[Validations]
end
subgraph "Lớp Domain"
AR[Aggregate Roots]
E[Entities]
VO[Value Objects]
DE[Domain Events]
DX[Domain Exceptions]
end
subgraph "Lớp Infrastructure"
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
Trách Nhiệm Các Lớp
1. Lớp Domain (MyService.Domain)
Trái tim của ứng dụng chứa business logic thuần túy. Lớp này:
- Có ZERO phụ thuộc bên ngoài (ngoại trừ MediatR.Contracts cho events)
- Chỉ chứa các class POCO
- Triển khai các tactical patterns của DDD
Thành Phần
| Thành phần | Mục Đích |
|---|---|
| SeedWork | Base classes: Entity, ValueObject, Enumeration, IAggregateRoot |
| AggregatesModel | Aggregate roots với entities và value objects |
| Events | Domain events cho giao tiếp cross-aggregate |
| Exceptions | Domain exceptions cho vi phạm business rules |
2. Lớp Infrastructure (MyService.Infrastructure)
Triển khai kỹ thuật và các mối quan tâm bên ngoài:
- Truy cập database (EF Core)
- Triển khai repositories
- Tích hợp external services
3. Lớp API (MyService.API)
Điểm vào ứng dụng và triển khai CQRS:
- Controllers để xử lý HTTP
- Commands cho các thao tác ghi
- Queries cho các thao tác đọc
- MediatR behaviors cho cross-cutting concerns
Luồng CQRS
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
graph LR
AR[Aggregate Root] -->|Phát sinh| DE[Domain Event]
DE -->|Dispatch bởi| CTX[DbContext]
CTX -->|Publish tới| M[MediatR]
M -->|Xử lý bởi| H1[Handler 1]
M -->|Xử lý bởi| 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
Schema Database
Sample Aggregate
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
Pipeline MediatR
Request → LoggingBehavior → ValidatorBehavior → TransactionBehavior → Handler → Response
│ │ │
▼ ▼ ▼
Log start/end Validate Begin/Commit
+ timing với Transaction
FluentValidation
Thứ Tự Behaviors
- LoggingBehavior - Ghi log xử lý request với timing
- ValidatorBehavior - Validate request sử dụng FluentValidation
- TransactionBehavior - Bao bọc command handlers trong database transactions
Xử Lý Lỗi
Phân Cấp Exceptions
Exception
└── DomainException
└── SampleDomainException
Problem Details (RFC 7807)
Tất cả lỗi được trả về theo định dạng Problem Details:
{
"type": "https://tools.ietf.org/html/rfc7807",
"title": "Lỗi Validation",
"status": 400,
"detail": "Một hoặc nhiều lỗi validation đã xảy ra.",
"errors": {
"Name": ["Tên là bắt buộc"]
}
}
Health Checks
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
Kiến Trúc Deployment
Docker Compose (Local)
services:
myservice-api:
build: .
ports: ["5000:8080"]
depends_on:
- postgres
- redis
postgres:
image: postgres:16-alpine
redis:
image: redis:7-alpine
Kubernetes (Production)
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
Cân Nhắc Bảo Mật
- Authentication: JWT Bearer token (cấu hình trong production)
- Authorization: Role-based access control
- Input Validation: FluentValidation trên tất cả requests
- SQL Injection: EF Core parameterized queries
- Secrets: Biến môi trường, không bao giờ trong code
Tối Ưu Hiệu Năng
- Connection Pooling: EF Core với Npgsql connection resilience
- Async/Await: Tất cả I/O operations đều async
- Response Caching: Thêm caching headers cho queries
- Database Indexes: Cấu hình trong EntityConfigurations