DI trong ứng dụng thực tế (FastAPI + SQLAlchemy + Redis)
"The real power of DI is revealed in real-world applications where infrastructure changes, services grow, and testability becomes critical. Theory is good — practice is better." — Mark Seemann
Bài viết này áp dụng tất cả những gì đã học về SOLID và DI để xây dựng một ứng dụng User Management hoàn chỉnh với FastAPI, SQLAlchemy (PostgreSQL), Redis cache, JWT authentication, email service, và background tasks. Mục tiêu: cho thấy DI hoạt động như thế nào trong một ứng dụng production-grade, với đầy đủ các tầng (layers), các dependency được inject qua constructor, và một DI Container đơn giản quản lý toàn bộ.
Kiến trúc tổng quan
user-management/
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI app entry point
│ ├── container.py # DI Container
│ ├── config.py # Configuration management
│ │
│ ├── domain/ # Business logic (core)
│ │ ├── __init__.py
│ │ ├── models.py # Domain models
│ │ ├── interfaces.py # Abstract interfaces (ports)
│ │ ├── services/
│ │ │ ├── __init__.py
│ │ │ ├── user_service.py # UserService — use case
│ │ │ └── auth_service.py # AuthService — authentication
│ │ └── exceptions.py # Domain exceptions
│ │
│ ├── infrastructure/ # External implementations (adapters)
│ │ ├── __init__.py
│ │ ├── database.py # SQLAlchemy engine + session
│ │ ├── repositories/
│ │ │ ├── __init__.py
│ │ │ └── user_repository.py # PostgreSQL UserRepository
│ │ ├── cache.py # Redis cache
│ │ ├── email.py # Email service (SMTP / SendGrid)
│ │ ├── auth.py # JWT token service