Files
pos-system/services/_template_dot_net/ARCHITECTURE.md
Ho Ngoc Hai 0b0241143a feat(docs): Enhance Vietnamese documentation with updated diagrams and troubleshooting sections
- Improved Mermaid diagrams for better visual clarity and consistency across guides.
- Added detailed troubleshooting sections to assist users in diagnosing common issues effectively.
- Updated formatting and structure to align with the English version, ensuring consistency.
- Included quick tips and common issues sections to facilitate user navigation.
2026-01-10 21:21:41 +07:00

9.0 KiB

.NET Service Architecture / Kiến Trúc Dịch Vụ .NET

EN: Comprehensive architecture documentation for .NET microservices
VI: Tài liệu kiến trúc toàn diện cho microservices .NET

Table of Contents / Mục Lục

Clean Architecture Overview

EN: This template implements Clean Architecture (also known as Onion Architecture or Hexagonal Architecture) to achieve:

  • Independence of Frameworks: Business logic doesn't depend on frameworks
  • Testability: Business rules can be tested without UI, database, or external services
  • Independence of UI: UI can change without changing business rules
  • Independence of Database: Business rules are not bound to database
  • Independence of External Services: Business rules don't know about external services

VI: Template này triển khai Clean Architecture (còn gọi là Onion Architecture hoặc Hexagonal Architecture) để đạt được:

  • Độc lập với Frameworks: Business logic không phụ thuộc vào frameworks
  • Khả năng kiểm thử: Business rules có thể được test mà không cần UI, database hoặc external services
  • Độc lập với UI: UI có thể thay đổi mà không ảnh hưởng business rules
  • Độc lập với Database: Business rules không bị ràng buộc với database
  • Độc lập với External Services: Business rules không biết về external services

Layer Responsibilities / Trách Nhiệm Các Lớp

1. Domain Layer (Core) / Lớp Domain (Lõi)

EN: The innermost layer containing enterprise business rules.

VI: Lớp trong cùng chứa các business rules của doanh nghiệp.

Contains / Chứa:

  • Entities / Thực thể
  • Value Objects
  • Domain Events
  • Repository Interfaces
  • Domain Services Interfaces

No dependencies / Không phụ thuộc: This layer has no dependencies on other layers.

2. Application Layer / Lớp Application

EN: Contains application-specific business rules and orchestrates workflows.

VI: Chứa các business rules cụ thể của ứng dụng và điều phối workflows.

Contains / Chứa:

  • DTOs (Data Transfer Objects)
  • Service Interfaces
  • Service Implementations
  • Validators (FluentValidation)
  • Mappers (AutoMapper)

Dependencies / Phụ thuộc: Domain layer only

3. Infrastructure Layer / Lớp Infrastructure

EN: Contains implementation details for external concerns.

VI: Chứa implementation details cho các concerns bên ngoài.

Contains / Chứa:

  • DbContext (Entity Framework Core)
  • Repository Implementations
  • External Service Clients
  • Cache Implementations
  • File Storage Implementations

Dependencies / Phụ thuộc: Domain layer

4. API Layer (Presentation) / Lớp API (Presentation)

EN: Contains all the entry points to the application.

VI: Chứa tất cả các điểm vào của ứng dụng.

Contains / Chứa:

  • Controllers
  • Middleware
  • Filters
  • Configuration
  • Startup/Program.cs

Dependencies / Phụ thuộc: Application and Infrastructure layers

Dependency Flow / Luồng Phụ Thuộc

┌─────────────────────────────────────────┐
│         API Layer (Presentation)         │
│   Controllers, Middleware, Config        │
└───────────────┬─────────────────────────┘
                │
                ▼
┌─────────────────────────────────────────┐
│       Application Layer                  │
│   Services, DTOs, Validators             │
└──────────┬──────────────────────┬────────┘
           │                      │
           ▼                      ▼
┌──────────────────┐   ┌─────────────────────┐
│ Domain Layer     │   │ Infrastructure      │
│ Entities,        │◄──│ DbContext, Repos,   │
│ Interfaces       │   │ External Services   │
└──────────────────┘   └─────────────────────┘

EN: All dependencies point inward. The Domain layer has no dependencies on any other layer.

VI: Tất cả dependencies đều hướng vào trong. Lớp Domain không phụ thuộc vào bất kỳ lớp nào khác.

Design Patterns / Mẫu Thiết Kế

Repository Pattern

EN: Abstracts data access logic and provides a collection-like interface for accessing domain objects.

VI: Trừu tượng hóa logic truy cập dữ liệu và cung cấp interface giống collection để truy cập domain objects.

// Domain Layer - Interface
public interface IUserRepository
{
    Task<User?> GetByIdAsync(Guid id);
    Task<IEnumerable<User>> GetAllAsync();
    Task AddAsync(User user);
    Task UpdateAsync(User user);
    Task DeleteAsync(Guid id);
}

// Infrastructure Layer - Implementation
public class UserRepository : IUserRepository
{
    private readonly ApplicationDbContext _context;
    
    public UserRepository(ApplicationDbContext context)
    {
        _context = context;
    }
    
    public async Task<User?> GetByIdAsync(Guid id)
    {
        return await _context.Users.FindAsync(id);
    }
    // ... other implementations
}

Service Pattern

EN: Encapsulates business logic and orchestrates operations across repositories.

VI: Đóng gói business logic và điều phối các operations giữa các repositories.

// Application Layer
public interface IUserService
{
    Task<UserDto> GetUserAsync(Guid id);
    Task<UserDto> CreateUserAsync(CreateUserDto dto);
}

public class UserService : IUserService
{
    private readonly IUserRepository _userRepository;
    private readonly IMapper _mapper;
    
    public UserService(IUserRepository userRepository, IMapper mapper)
    {
        _userRepository = userRepository;
        _mapper = mapper;
    }
    
    public async Task<UserDto> GetUserAsync(Guid id)
    {
        var user = await _userRepository.GetByIdAsync(id);
        if (user == null) throw new NotFoundException("User not found");
        
        return _mapper.Map<UserDto>(user);
    }
}

Unit of Work Pattern

EN: Maintains a list of objects affected by a business transaction and coordinates writing changes.

VI: Duy trì danh sách các objects bị ảnh hưởng bởi một business transaction và điều phối việc ghi thay đổi.

CQRS (Command Query Responsibility Segregation)

EN: Optional pattern for separating read and write operations.

VI: Pattern tùy chọn để tách biệt các operations đọc và ghi.

Best Practices / Thực Hành Tốt

1. Dependency Injection

// EN: Register services in Program.cs
// VI: Đăng ký services trong Program.cs
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IUserService, UserService>();

2. Async/Await

// EN: Always use async for I/O operations
// VI: Luôn dùng async cho I/O operations
public async Task<User> GetUserAsync(Guid id)
{
    return await _context.Users.FindAsync(id);
}

3. Error Handling

// EN: Create custom exceptions
// VI: Tạo custom exceptions
public class NotFoundException : Exception
{
    public NotFoundException(string message) : base(message) { }
}

// EN: Global exception handler middleware
// VI: Middleware xử lý exception toàn cục
public class ExceptionMiddleware
{
    // ... implementation
}

4. Validation

// EN: Use FluentValidation for input validation
// VI: Dùng FluentValidation để validate input
public class CreateUserDtoValidator : AbstractValidator<CreateUserDto>
{
    public CreateUserDtoValidator()
    {
        RuleFor(x => x.Email).NotEmpty().EmailAddress();
        RuleFor(x => x.Password).MinimumLength(8);
    }
}

Testing Strategy / Chiến Lược Testing

EN:

  • Unit Tests: Test business logic in isolation
  • Integration Tests: Test layer interactions
  • E2E Tests: Test complete workflows

VI:

  • Unit Tests: Test business logic độc lập
  • Integration Tests: Test tương tác giữa các lớp
  • E2E Tests: Test toàn bộ workflows

Resources / Tài Nguyên