# 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 ```bash # 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 ```bash cp .env.example .env nano .env ``` ### 3. Chạy với Docker ```bash docker-compose up -d docker-compose logs -f myservice-api ``` ### 4. Chạy Local ```bash 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 ```mermaid 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) ```csharp public record CreateSampleCommand(string Name, string? Description) : IRequest; public class CreateSampleCommandHandler : IRequestHandler { public async Task 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ử ```bash # 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 ```bash docker build -t myservice:latest . docker run -p 5000:8080 --env-file .env myservice:latest ``` ### Kubernetes ```yaml 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) ## Tài Liệu Liên Quan - [Chi Tiết Kiến Trúc](../architecture/microservices-communication.md) - [DDD Patterns](../architecture/system-design.md) - [Hướng Dẫn Triển Khai](../guides/deployment.md) ## Tài Nguyên - [eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers) - [Tài liệu .NET 10](https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-10) - [MediatR](https://github.com/jbogard/MediatR) - [FluentValidation](https://docs.fluentvalidation.net/)