- Simplified the .env.example file by removing outdated comments and consolidating environment variable descriptions. - Updated the architecture documentation to reflect the new structure and components of the .NET 10 microservice template. - Enhanced clarity in the README.md to provide a more comprehensive overview of the template's features and requirements. - Removed obsolete appsettings files to streamline the project structure and improve usability.
.NET 10 Microservice Template / Template Microservice .NET 10
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.
Overview / Tổng Quan
EN: 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
- Clean Architecture - Domain, Infrastructure, API layered separation
- EF Core 10 - PostgreSQL with connection resilience
- FluentValidation - Request validation
- API Versioning - URL segment versioning
- 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
| Requirement | Version |
|---|---|
| .NET SDK | 10.0.101+ |
| Docker | 24.0+ |
| PostgreSQL | 15+ (or use Docker) |
# Check .NET version / Kiểm tra phiên bản .NET
dotnet --version
# Should output: 10.0.xxx
Quick Start / Bắt Đầu Nhanh
1. Create New Service / Tạo Service Mới
# EN: Copy template to new service
# VI: Sao chép template sang service mới
cp -r services/_template_dot_net services/your-service-name
# EN: Navigate to service directory
# VI: Di chuyển đến thư mục service
cd services/your-service-name
# EN: Rename all occurrences of "MyService" to "YourService"
# VI: Đổ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. Configure Environment / Cấu Hình Môi Trường
# EN: Copy environment template
# VI: Sao chép template môi trường
cp .env.example .env
# EN: Edit with your configuration
# VI: Chỉnh sửa với cấu hình của bạn
nano .env
3. Run with Docker / Chạy với Docker
# EN: Start all services (API + PostgreSQL + Redis)
# VI: Khởi động tất cả services (API + PostgreSQL + Redis)
docker-compose up -d
# EN: View logs
# VI: Xem logs
docker-compose logs -f myservice-api
4. Run Locally / Chạy Local
# EN: Restore dependencies
# VI: Khôi phục dependencies
dotnet restore
# EN: Build all projects
# VI: Build tất cả projects
dotnet build
# EN: Run the API
# VI: Chạy API
dotnet run --project src/MyService.API
Project Structure / Cấu Trúc Dự Án
_template_dot_net/
├── src/
│ ├── MyService.API/ # Presentation Layer (Controllers, CQRS)
│ │ ├── Controllers/ # API endpoints
│ │ ├── Application/ # CQRS Implementation
│ │ │ ├── Commands/ # Write operations (MediatR)
│ │ │ ├── Queries/ # Read operations
│ │ │ ├── Behaviors/ # MediatR pipeline behaviors
│ │ │ └── Validations/ # FluentValidation validators
│ │ ├── Middleware/ # Custom middleware
│ │ └── Program.cs # Application entry point
│ │
│ ├── MyService.Domain/ # Domain Layer (Pure business logic)
│ │ ├── AggregatesModel/ # Aggregate roots and entities
│ │ ├── Events/ # Domain events
│ │ ├── Exceptions/ # Domain exceptions
│ │ └── SeedWork/ # Base classes (Entity, ValueObject, etc.)
│ │
│ └── MyService.Infrastructure/ # Infrastructure Layer (Data access)
│ ├── EntityConfigurations/ # EF Core Fluent API configurations
│ ├── Repositories/ # Repository implementations
│ ├── Idempotency/ # Request idempotency handling
│ └── MyServiceContext.cs # DbContext with Unit of Work
│
├── tests/
│ ├── MyService.UnitTests/ # Unit tests (Domain, Application)
│ └── MyService.FunctionalTests/ # Integration tests (API endpoints)
│
├── Dockerfile # Multi-stage Docker build
├── docker-compose.yml # Local development setup
├── global.json # .NET SDK version pinning
└── Directory.Build.props # Common MSBuild properties
API Endpoints / Các Endpoint API
| 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 |
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 |
CQRS Pattern / Pattern CQRS
Commands (Write Operations)
// Define command / Định nghĩa command
public record CreateSampleCommand(string Name, string? Description)
: IRequest<CreateSampleCommandResult>;
// Handle command / Xử lý command
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);
}
}
Queries (Read Operations)
// Define query / Định nghĩa query
public record GetSampleQuery(Guid SampleId) : IRequest<SampleViewModel?>;
Domain Model / Domain Model
Aggregate Root
public class Sample : Entity, IAggregateRoot
{
public string Name => _name;
public SampleStatus Status => _status;
public Sample(string name, string? description) {
// Business logic validation
if (string.IsNullOrWhiteSpace(name))
throw new SampleDomainException("Sample name cannot be empty");
// Domain event
AddDomainEvent(new SampleCreatedDomainEvent(this));
}
public void Activate() {
if (_status != SampleStatus.Draft)
throw new SampleDomainException("Only draft samples can be activated");
// State transition
}
}
Testing / Kiểm Thử
# EN: Run all tests
# VI: Chạy tất cả tests
dotnet test
# EN: Run with coverage
# VI: Chạy với coverage
dotnet test /p:CollectCoverage=true /p:CoverageReportFormat=cobertura
# EN: Run specific test project
# VI: Chạy project test cụ thể
dotnet test tests/MyService.UnitTests
Configuration / Cấu Hình
Environment Variables
| Variable | Description / Mô Tả | Default |
|---|---|---|
ASPNETCORE_ENVIRONMENT |
Environment name | Development |
DATABASE_URL |
PostgreSQL connection string | - |
REDIS_URL |
Redis connection string | - |
JWT_SECRET |
JWT signing secret (min 32 chars) | - |
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Database=myservice;Username=postgres;Password=postgres"
},
"Serilog": {
"MinimumLevel": "Information"
}
}
Deployment / Triển Khai
Docker Build
# EN: Build Docker image
# VI: Build Docker image
docker build -t myservice:latest .
# EN: Run container
# VI: Chạy container
docker run -p 5000:8080 --env-file .env myservice:latest
Kubernetes
See ARCHITECTURE.md for Kubernetes deployment manifests.
What's New in .NET 10 / Có Gì Mới Trong .NET 10
- C# 14 language features
- Improved Native AOT support
- Better async/await performance
- Enhanced JSON serialization
- Performance improvements across the board
- 3-year LTS support (until November 2028)
Resources / Tài Nguyên
- eShopOnContainers - Reference architecture
- .NET 10 Documentation
- DDD with .NET
- MediatR - CQRS library
- FluentValidation - Validation library
License / Giấy Phép
Proprietary - GoodGo Platform