- Enhanced Mermaid diagrams for better visual clarity and consistency across guides. - Added new sections on caching, data consistency, and observability patterns to the architecture documentation. - Improved formatting and structure to align with the English version, ensuring a cohesive user experience. - Removed outdated service communication documentation to reduce clutter and focus on relevant content.
7.8 KiB
7.8 KiB
Template Microservice .NET 10
Template microservice .NET 10 cấp doanh nghiệp theo các pattern DDD, CQRS và Clean Architecture.
Tổng Quan
Template này cung cấp cấu trúc sẵn sàng production cho microservices .NET dựa trên kiến trúc tham chiếu eShopOnContainers với:
- Domain-Driven Design (DDD) - Aggregates, Entities, Value Objects, Domain Events
- CQRS Pattern - Tách biệt Commands (ghi) và Queries (đọc) với MediatR
- Clean Architecture - Phân tầng Domain, Infrastructure, API
- EF Core 10 - PostgreSQL với connection resilience
- FluentValidation - Validation request
- API Versioning - Versioning theo URL segment
- Health Checks - Probes sẵn sàng cho Kubernetes
- Structured Logging - Serilog với console và Seq
Yêu Cầu
| Yêu cầu | Phiên bản |
|---|---|
| .NET SDK | 10.0.101+ |
| Docker | 24.0+ |
| PostgreSQL | 15+ (hoặc dùng Docker) |
Bắt Đầu Nhanh
1. Tạo Service Mới
# Sao chép template sang service mới
cp -r services/_template_dot_net services/your-service-name
cd services/your-service-name
# Đổi tên tất cả "MyService" thành "YourService"
find . -type f -name "*.cs" -exec sed -i '' 's/MyService/YourService/g' {} +
find . -type f -name "*.csproj" -exec sed -i '' 's/MyService/YourService/g' {} +
2. Cấu Hình Môi Trường
cp .env.example .env
nano .env
3. Chạy với Docker
docker-compose up -d
docker-compose logs -f myservice-api
4. Chạy Local
dotnet restore
dotnet build
dotnet run --project src/MyService.API
Cấu Trúc Dự Án
_template_dot_net/
├── src/
│ ├── MyService.API/ # Lớp Presentation (Controllers, CQRS)
│ │ ├── Controllers/ # Các API endpoints
│ │ ├── Application/ # Triển khai CQRS
│ │ │ ├── Commands/ # Thao tác ghi (MediatR)
│ │ │ ├── Queries/ # Thao tác đọc
│ │ │ ├── Behaviors/ # MediatR pipeline behaviors
│ │ │ └── Validations/ # FluentValidation validators
│ │ └── Program.cs # Điểm vào ứng dụng
│ │
│ ├── MyService.Domain/ # Lớp Domain (Business logic thuần túy)
│ │ ├── AggregatesModel/ # Aggregate roots và entities
│ │ ├── Events/ # Domain events
│ │ ├── Exceptions/ # Domain exceptions
│ │ └── SeedWork/ # Base classes
│ │
│ └── MyService.Infrastructure/ # Lớp Infrastructure
│ ├── EntityConfigurations/ # Cấu hình EF Core
│ ├── Repositories/ # Triển khai repositories
│ └── MyServiceContext.cs # DbContext với Unit of Work
│
├── tests/
│ ├── MyService.UnitTests/ # Unit tests
│ └── MyService.FunctionalTests/ # Integration tests
│
├── Dockerfile # Multi-stage Docker build
└── docker-compose.yml # Thiết lập phát triển local
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]
end
subgraph "Lớp Infrastructure"
DB[(PostgreSQL)]
R[Repositories]
CTX[DbContext]
end
C --> CMD
C --> Q
CMD --> B --> V
CMD --> AR
Q --> R
R --> CTX --> DB
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
- ZERO phụ thuộc bên ngoài (ngoại trừ MediatR.Contracts)
- Chỉ chứa các class POCO
- Triển khai các tactical patterns của DDD
| Thành phần | Mục Đích |
|---|---|
| SeedWork | Base classes: Entity, ValueObject, IAggregateRoot |
| AggregatesModel | Aggregate roots với entities và value objects |
| Events | Domain events cho giao tiếp cross-aggregate |
| Exceptions | Domain exceptions |
2. Lớp Infrastructure
- Truy cập database (EF Core)
- Triển khai repositories
- Tích hợp external services
3. Lớp API
- 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
Pattern CQRS
Commands (Thao Tác Ghi)
public record CreateSampleCommand(string Name, string? Description)
: IRequest<CreateSampleCommandResult>;
public class CreateSampleCommandHandler : IRequestHandler<CreateSampleCommand, CreateSampleCommandResult>
{
public async Task<CreateSampleCommandResult> Handle(CreateSampleCommand request, CancellationToken ct)
{
var sample = new Sample(request.Name, request.Description);
_repository.Add(sample);
await _repository.UnitOfWork.SaveEntitiesAsync(ct);
return new CreateSampleCommandResult(sample.Id);
}
}
Pipeline MediatR
Request → LoggingBehavior → ValidatorBehavior → TransactionBehavior → Handler → Response
Các API Endpoints
| Method | Endpoint | Mô Tả |
|---|---|---|
GET |
/api/v1/samples |
Lấy tất cả samples |
GET |
/api/v1/samples/{id} |
Lấy sample theo ID |
POST |
/api/v1/samples |
Tạo sample mới |
PUT |
/api/v1/samples/{id} |
Cập nhật sample |
DELETE |
/api/v1/samples/{id} |
Xóa sample |
PATCH |
/api/v1/samples/{id}/status |
Thay đổi trạng thái |
Health Endpoints
| Endpoint | Mục Đích |
|---|---|
/health |
Trạng thái health đầy đủ |
/health/live |
Kiểm tra sống |
/health/ready |
Kiểm tra sẵn sàng |
Biến Môi Trường
| Biến | Mô Tả | Mặc định |
|---|---|---|
ASPNETCORE_ENVIRONMENT |
Tên môi trường | Development |
DATABASE_URL |
Kết nối PostgreSQL | - |
REDIS_URL |
Kết nối Redis | - |
JWT_SECRET |
Secret ký JWT | - |
Kiểm Thử
# Chạy tất cả tests
dotnet test
# Chạy với coverage
dotnet test /p:CollectCoverage=true /p:CoverageReportFormat=cobertura
# Chạy project test cụ thể
dotnet test tests/MyService.UnitTests
Triển Khai
Docker Build
docker build -t myservice:latest .
docker run -p 5000:8080 --env-file .env myservice:latest
Kubernetes
apiVersion: apps/v1
kind: Deployment
metadata:
name: myservice-api
spec:
replicas: 3
template:
spec:
containers:
- name: api
image: myservice:latest
livenessProbe:
httpGet:
path: /health/live
port: 8080
readinessProbe:
httpGet:
path: /health/ready
port: 8080
Có Gì Mới Trong .NET 10
- Tính năng ngôn ngữ C# 14
- Hỗ trợ Native AOT được cải thiện
- Hiệu suất async/await tốt hơn
- JSON serialization được nâng cao
- Hỗ trợ LTS 3 năm (đến tháng 11/2028)