From 66d87ac865b5d38fd956377e691ad58739214ed5 Mon Sep 17 00:00:00 2001 From: Ho Ngoc Hai Date: Mon, 12 Jan 2026 12:22:54 +0700 Subject: [PATCH] feat(docs): Remove ARCHITECTURE.md and README.md for project simplification - Deleted ARCHITECTURE.md and README.md files to streamline the project structure and eliminate outdated documentation. - This change aims to enhance usability and focus on more relevant resources for users. --- .../{ => docs/en}/ARCHITECTURE.md | 67 ++--- .../_template_dot_net/{ => docs/en}/README.md | 135 ++++----- .../_template_dot_net/docs/vi/ARCHITECTURE.md | 271 ++++++++++++++++++ services/_template_dot_net/docs/vi/README.md | 265 +++++++++++++++++ 4 files changed, 615 insertions(+), 123 deletions(-) rename services/_template_dot_net/{ => docs/en}/ARCHITECTURE.md (76%) rename services/_template_dot_net/{ => docs/en}/README.md (61%) create mode 100644 services/_template_dot_net/docs/vi/ARCHITECTURE.md create mode 100644 services/_template_dot_net/docs/vi/README.md diff --git a/services/_template_dot_net/ARCHITECTURE.md b/services/_template_dot_net/docs/en/ARCHITECTURE.md similarity index 76% rename from services/_template_dot_net/ARCHITECTURE.md rename to services/_template_dot_net/docs/en/ARCHITECTURE.md index c07bae76..9d80ba57 100644 --- a/services/_template_dot_net/ARCHITECTURE.md +++ b/services/_template_dot_net/docs/en/ARCHITECTURE.md @@ -1,13 +1,12 @@ -# Architecture Documentation / Tài Liệu Kiến Trúc +# Architecture Documentation -> **EN**: Detailed architecture documentation for the .NET 10 Microservice Template. -> **VI**: Tài liệu kiến trúc chi tiết cho Template Microservice .NET 10. +> Detailed architecture documentation for the .NET 10 Microservice Template. -## Architecture Overview / Tổng Quan Kiến Trúc +## Architecture Overview ```mermaid graph TB - subgraph "API Layer / Lớp API" + subgraph "API Layer" C[Controllers] CMD[Commands] Q[Queries] @@ -15,7 +14,7 @@ graph TB V[Validations] end - subgraph "Domain Layer / Lớp Domain" + subgraph "Domain Layer" AR[Aggregate Roots] E[Entities] VO[Value Objects] @@ -23,7 +22,7 @@ graph TB DX[Domain Exceptions] end - subgraph "Infrastructure Layer / Lớp Infrastructure" + subgraph "Infrastructure Layer" DB[(PostgreSQL)] R[Repositories] CTX[DbContext] @@ -44,24 +43,19 @@ graph TB style DB fill:#ff6b6b,stroke:#c0392b,color:#fff ``` -## Layer Responsibilities / Trách Nhiệm Các Lớp +## Layer Responsibilities ### 1. Domain Layer (MyService.Domain) -**EN**: The heart of the application containing pure business logic. This layer: +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 -**VI**: 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 +#### Components -#### Components / Thành Phần - -| Component | Purpose / Mục Đích | -|-----------|-------------------| +| 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 | @@ -69,31 +63,20 @@ graph TB ### 2. Infrastructure Layer (MyService.Infrastructure) -**EN**: Technical implementations and external concerns: +Technical implementations and external concerns: - Database access (EF Core) - Repository implementations - External service integrations -**VI**: 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. API Layer (MyService.API) -**EN**: Application entry point and CQRS implementation: +Application entry point and CQRS implementation: - Controllers for HTTP handling - Commands for write operations - Queries for read operations - MediatR behaviors for cross-cutting concerns -**VI**: Đ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 - -## CQRS Flow / Luồng CQRS +## CQRS Flow ```mermaid sequenceDiagram @@ -121,7 +104,7 @@ sequenceDiagram Controller-->>Client: HTTP Response ``` -## Domain Events / Domain Events +## Domain Events ```mermaid graph LR @@ -136,7 +119,7 @@ graph LR style M fill:#9b59b6,stroke:#7d3c98,color:#fff ``` -## Database Schema / Schema Database +## Database Schema ### Sample Aggregate @@ -159,7 +142,7 @@ erDiagram samples ||--o{ sample_statuses : has ``` -## MediatR Pipeline / Pipeline MediatR +## MediatR Pipeline ``` Request → LoggingBehavior → ValidatorBehavior → TransactionBehavior → Handler → Response @@ -170,15 +153,15 @@ Request → LoggingBehavior → ValidatorBehavior → TransactionBehavior → Ha FluentValidation ``` -### Behavior Order / Thứ Tự Behaviors +### 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 / Xử Lý Lỗi +## Error Handling -### Exception Hierarchy / Phân Cấp Exceptions +### Exception Hierarchy ``` Exception @@ -202,7 +185,7 @@ All errors are returned in Problem Details format: } ``` -## Health Checks / Health Checks +## Health Checks ```mermaid graph TD @@ -219,7 +202,7 @@ graph TD style R fill:#f39c12,stroke:#d68910,color:#fff ``` -## Deployment Architecture / Kiến Trúc Deployment +## Deployment Architecture ### Docker Compose (Local) @@ -265,7 +248,7 @@ spec: port: 8080 ``` -## Security Considerations / Cân Nhắc Bảo Mật +## Security Considerations 1. **Authentication**: JWT Bearer token (configure in production) 2. **Authorization**: Role-based access control @@ -273,14 +256,14 @@ spec: 4. **SQL Injection**: EF Core parameterized queries 5. **Secrets**: Environment variables, never in code -## Performance Optimization / Tối Ưu Hiệu Năng +## 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 / Tài Liệu Tham Khảo +## References - [eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers) - [.NET Microservices Architecture Guide](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/) diff --git a/services/_template_dot_net/README.md b/services/_template_dot_net/docs/en/README.md similarity index 61% rename from services/_template_dot_net/README.md rename to services/_template_dot_net/docs/en/README.md index 820c9d9c..4cb53d44 100644 --- a/services/_template_dot_net/README.md +++ b/services/_template_dot_net/docs/en/README.md @@ -1,11 +1,10 @@ -# .NET 10 Microservice Template / Template Microservice .NET 10 +# .NET 10 Microservice Template -> **EN**: Enterprise-grade .NET 10 microservice template following DDD, CQRS, and Clean Architecture patterns. -> **VI**: Template microservice .NET 10 cấp doanh nghiệp theo các pattern DDD, CQRS và Clean Architecture. +> Enterprise-grade .NET 10 microservice template following DDD, CQRS, and Clean Architecture patterns. -## Overview / Tổng Quan +## Overview -**EN**: This template provides a production-ready structure for .NET microservices based on the eShopOnContainers reference architecture with: +This template provides a production-ready structure for .NET microservices based on the eShopOnContainers reference architecture with: - **Domain-Driven Design (DDD)** - Aggregates, Entities, Value Objects, Domain Events - **CQRS Pattern** - Separate Commands (write) and Queries (read) with MediatR @@ -16,18 +15,7 @@ - **Health Checks** - Kubernetes-ready probes - **Structured Logging** - Serilog with console and Seq -**VI**: 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 - -## Prerequisites / Yêu Cầu +## Prerequisites | Requirement | Version | |-------------|---------| @@ -36,71 +24,61 @@ | PostgreSQL | 15+ (or use Docker) | ```bash -# Check .NET version / Kiểm tra phiên bản .NET +# Check .NET version dotnet --version # Should output: 10.0.xxx ``` -## Quick Start / Bắt Đầu Nhanh +## Quick Start -### 1. Create New Service / Tạo Service Mới +### 1. Create New Service ```bash -# EN: Copy template to new service -# VI: Sao chép template sang service mới +# Copy template to new service cp -r services/_template_dot_net services/your-service-name -# EN: Navigate to service directory -# VI: Di chuyển đến thư mục service +# Navigate to service directory cd services/your-service-name -# EN: Rename all occurrences of "MyService" to "YourService" -# VI: Đổi tên tất cả "MyService" thành "YourService" +# Rename all occurrences of "MyService" to "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. Configure Environment / Cấu Hình Môi Trường +### 2. Configure Environment ```bash -# EN: Copy environment template -# VI: Sao chép template môi trường +# Copy environment template cp .env.example .env -# EN: Edit with your configuration -# VI: Chỉnh sửa với cấu hình của bạn +# Edit with your configuration nano .env ``` -### 3. Run with Docker / Chạy với Docker +### 3. Run with Docker ```bash -# EN: Start all services (API + PostgreSQL + Redis) -# VI: Khởi động tất cả services (API + PostgreSQL + Redis) +# Start all services (API + PostgreSQL + Redis) docker-compose up -d -# EN: View logs -# VI: Xem logs +# View logs docker-compose logs -f myservice-api ``` -### 4. Run Locally / Chạy Local +### 4. Run Locally ```bash -# EN: Restore dependencies -# VI: Khôi phục dependencies +# Restore dependencies dotnet restore -# EN: Build all projects -# VI: Build tất cả projects +# Build all projects dotnet build -# EN: Run the API -# VI: Chạy API +# Run the API dotnet run --project src/MyService.API ``` -## Project Structure / Cấu Trúc Dự Án +## Project Structure ``` _template_dot_net/ @@ -137,35 +115,35 @@ _template_dot_net/ └── Directory.Build.props # Common MSBuild properties ``` -## API Endpoints / Các Endpoint API +## API Endpoints -| Method | Endpoint | Description / Mô Tả | -|--------|----------|---------------------| -| `GET` | `/api/v1/samples` | Get all samples / Lấy tất cả samples | -| `GET` | `/api/v1/samples/{id}` | Get sample by ID / Lấy sample theo ID | -| `POST` | `/api/v1/samples` | Create new sample / Tạo sample mới | -| `PUT` | `/api/v1/samples/{id}` | Update sample / Cập nhật sample | -| `DELETE` | `/api/v1/samples/{id}` | Delete sample / Xóa sample | -| `PATCH` | `/api/v1/samples/{id}/status` | Change status / Thay đổi trạng thái | +| Method | Endpoint | Description | +|--------|----------|-------------| +| `GET` | `/api/v1/samples` | Get all samples | +| `GET` | `/api/v1/samples/{id}` | Get sample by ID | +| `POST` | `/api/v1/samples` | Create new sample | +| `PUT` | `/api/v1/samples/{id}` | Update sample | +| `DELETE` | `/api/v1/samples/{id}` | Delete sample | +| `PATCH` | `/api/v1/samples/{id}/status` | Change status | ### Health Endpoints -| Endpoint | Purpose / Mục Đích | -|----------|-------------------| -| `/health` | Full health status / Trạng thái health đầy đủ | -| `/health/live` | Liveness probe / Kiểm tra sống | -| `/health/ready` | Readiness probe / Kiểm tra sẵn sàng | +| Endpoint | Purpose | +|----------|---------| +| `/health` | Full health status | +| `/health/live` | Liveness probe | +| `/health/ready` | Readiness probe | -## CQRS Pattern / Pattern CQRS +## CQRS Pattern ### Commands (Write Operations) ```csharp -// Define command / Định nghĩa command +// Define command public record CreateSampleCommand(string Name, string? Description) : IRequest; -// Handle command / Xử lý command +// Handle command public class CreateSampleCommandHandler : IRequestHandler { public async Task Handle(CreateSampleCommand request, CancellationToken ct) @@ -181,11 +159,11 @@ public class CreateSampleCommandHandler : IRequestHandler; ``` -## Domain Model / Domain Model +## Domain Model ### Aggregate Root @@ -212,28 +190,25 @@ public class Sample : Entity, IAggregateRoot } ``` -## Testing / Kiểm Thử +## Testing ```bash -# EN: Run all tests -# VI: Chạy tất cả tests +# Run all tests dotnet test -# EN: Run with coverage -# VI: Chạy với coverage +# Run with coverage dotnet test /p:CollectCoverage=true /p:CoverageReportFormat=cobertura -# EN: Run specific test project -# VI: Chạy project test cụ thể +# Run specific test project dotnet test tests/MyService.UnitTests ``` -## Configuration / Cấu Hình +## Configuration ### Environment Variables -| Variable | Description / Mô Tả | Default | -|----------|---------------------|---------| +| Variable | Description | Default | +|----------|-------------|---------| | `ASPNETCORE_ENVIRONMENT` | Environment name | `Development` | | `DATABASE_URL` | PostgreSQL connection string | - | | `REDIS_URL` | Redis connection string | - | @@ -252,17 +227,15 @@ dotnet test tests/MyService.UnitTests } ``` -## Deployment / Triển Khai +## Deployment ### Docker Build ```bash -# EN: Build Docker image -# VI: Build Docker image +# Build Docker image docker build -t myservice:latest . -# EN: Run container -# VI: Chạy container +# Run container docker run -p 5000:8080 --env-file .env myservice:latest ``` @@ -270,7 +243,7 @@ docker run -p 5000:8080 --env-file .env myservice:latest See [ARCHITECTURE.md](./ARCHITECTURE.md) for Kubernetes deployment manifests. -## What's New in .NET 10 / Có Gì Mới Trong .NET 10 +## What's New in .NET 10 - **C# 14** language features - Improved **Native AOT** support @@ -279,7 +252,7 @@ See [ARCHITECTURE.md](./ARCHITECTURE.md) for Kubernetes deployment manifests. - Performance improvements across the board - 3-year **LTS** support (until November 2028) -## Resources / Tài Nguyên +## Resources - [eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers) - Reference architecture - [.NET 10 Documentation](https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-10) @@ -287,6 +260,6 @@ See [ARCHITECTURE.md](./ARCHITECTURE.md) for Kubernetes deployment manifests. - [MediatR](https://github.com/jbogard/MediatR) - CQRS library - [FluentValidation](https://docs.fluentvalidation.net/) - Validation library -## License / Giấy Phép +## License Proprietary - GoodGo Platform diff --git a/services/_template_dot_net/docs/vi/ARCHITECTURE.md b/services/_template_dot_net/docs/vi/ARCHITECTURE.md new file mode 100644 index 00000000..55a5d13b --- /dev/null +++ b/services/_template_dot_net/docs/vi/ARCHITECTURE.md @@ -0,0 +1,271 @@ +# 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 + +```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] + 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 + +```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] -->|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 + +```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 +``` + +## Pipeline MediatR + +``` +Request → LoggingBehavior → ValidatorBehavior → TransactionBehavior → Handler → Response + │ │ │ + ▼ ▼ ▼ + Log start/end Validate Begin/Commit + + timing với Transaction + FluentValidation +``` + +### Thứ Tự Behaviors + +1. **LoggingBehavior** - Ghi log xử lý request với timing +2. **ValidatorBehavior** - Validate request sử dụng FluentValidation +3. **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: + +```json +{ + "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 + +```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 +``` + +## Kiến Trúc Deployment + +### 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 +``` + +## Cân Nhắc Bảo Mật + +1. **Authentication**: JWT Bearer token (cấu hình trong production) +2. **Authorization**: Role-based access control +3. **Input Validation**: FluentValidation trên tất cả requests +4. **SQL Injection**: EF Core parameterized queries +5. **Secrets**: Biến môi trường, không bao giờ trong code + +## Tối Ưu Hiệu Năng + +1. **Connection Pooling**: EF Core với Npgsql connection resilience +2. **Async/Await**: Tất cả I/O operations đều async +3. **Response Caching**: Thêm caching headers cho queries +4. **Database Indexes**: Cấu hình trong EntityConfigurations + +## Tài Liệu Tham Khảo + +- [eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers) +- [Hướng dẫn Kiến trúc .NET Microservices](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) diff --git a/services/_template_dot_net/docs/vi/README.md b/services/_template_dot_net/docs/vi/README.md new file mode 100644 index 00000000..7d7e48b6 --- /dev/null +++ b/services/_template_dot_net/docs/vi/README.md @@ -0,0 +1,265 @@ +# 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) | + +```bash +# Kiểm tra phiên bản .NET +dotnet --version +# Kết quả nên là: 10.0.xxx +``` + +## 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 + +# Di chuyển đến thư mục service +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 +# Sao chép template môi trường +cp .env.example .env + +# Chỉnh sửa với cấu hình của bạn +nano .env +``` + +### 3. Chạy với Docker + +```bash +# Khởi động tất cả services (API + PostgreSQL + Redis) +docker-compose up -d + +# Xem logs +docker-compose logs -f myservice-api +``` + +### 4. Chạy Local + +```bash +# Khôi phục dependencies +dotnet restore + +# Build tất cả projects +dotnet build + +# Chạy API +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 +│ │ ├── Middleware/ # Custom middleware +│ │ └── 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 (Entity, ValueObject, etc.) +│ │ +│ └── MyService.Infrastructure/ # Lớp Infrastructure (Truy cập dữ liệu) +│ ├── EntityConfigurations/ # Cấu hình EF Core Fluent API +│ ├── Repositories/ # Triển khai repositories +│ ├── Idempotency/ # Xử lý idempotency request +│ └── MyServiceContext.cs # DbContext với Unit of Work +│ +├── tests/ +│ ├── MyService.UnitTests/ # Unit tests (Domain, Application) +│ └── MyService.FunctionalTests/ # Integration tests (API endpoints) +│ +├── Dockerfile # Multi-stage Docker build +├── docker-compose.yml # Thiết lập phát triển local +├── global.json # Pin phiên bản .NET SDK +└── Directory.Build.props # Thuộc tính MSBuild chung +``` + +## Các Endpoint API + +| 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 | + +## Pattern CQRS + +### Commands (Thao Tác Ghi) + +```csharp +// Định nghĩa command +public record CreateSampleCommand(string Name, string? Description) + : IRequest; + +// Xử lý command +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); + } +} +``` + +### Queries (Thao Tác Đọc) + +```csharp +// Định nghĩa query +public record GetSampleQuery(Guid SampleId) : IRequest; +``` + +## Domain Model + +### Aggregate Root + +```csharp +public class Sample : Entity, IAggregateRoot +{ + public string Name => _name; + public SampleStatus Status => _status; + + public Sample(string name, string? description) { + // Validation business logic + if (string.IsNullOrWhiteSpace(name)) + throw new SampleDomainException("Tên sample không được để trống"); + + // Domain event + AddDomainEvent(new SampleCreatedDomainEvent(this)); + } + + public void Activate() { + if (_status != SampleStatus.Draft) + throw new SampleDomainException("Chỉ sample draft mới có thể kích hoạt"); + // Chuyển đổi trạng thái + } +} +``` + +## 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 +``` + +## Cấu Hình + +### Biến Môi Trường + +| Biến | Mô Tả | Mặc định | +|------|-------|----------| +| `ASPNETCORE_ENVIRONMENT` | Tên môi trường | `Development` | +| `DATABASE_URL` | Connection string PostgreSQL | - | +| `REDIS_URL` | Connection string Redis | - | +| `JWT_SECRET` | Secret ký JWT (tối thiểu 32 ký tự) | - | + +### appsettings.json + +```json +{ + "ConnectionStrings": { + "DefaultConnection": "Host=localhost;Database=myservice;Username=postgres;Password=postgres" + }, + "Serilog": { + "MinimumLevel": "Information" + } +} +``` + +## Triển Khai + +### Docker Build + +```bash +# Build Docker image +docker build -t myservice:latest . + +# Chạy container +docker run -p 5000:8080 --env-file .env myservice:latest +``` + +### Kubernetes + +Xem [ARCHITECTURE.md](./ARCHITECTURE.md) để biết manifests triển khai Kubernetes. + +## 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 +- Cải thiện hiệu suất toàn diện +- Hỗ trợ **LTS** 3 năm (đến tháng 11/2028) + +## Tài Nguyên + +- [eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers) - Kiến trúc tham chiếu +- [Tài liệu .NET 10](https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-10) +- [DDD với .NET](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/) +- [MediatR](https://github.com/jbogard/MediatR) - Thư viện CQRS +- [FluentValidation](https://docs.fluentvalidation.net/) - Thư viện validation + +## Giấy Phép + +Độc quyền - GoodGo Platform