Dependency Injection là gì?
ASP.NET Core MVC controllers request dependencies một cách explicit thông qua constructors. ASP.NET Core có built-in support cho dependency injection (DI). DI giúp ứng dụng dễ test và dễ bảo trì.Constructor Injection
Nguyên tắc cơ bản
Services được thêm như constructor parameters, và runtime resolve service từ service container. Services thường được định nghĩa dùng interfaces.Ví dụ: Interface và Implementation
Đăng ký Service
Controller sử dụng Constructor Injection
Lưu ý: Services thường được đăng ký dùng interfaces để:
- Giảm coupling giữa controller và implementation
- Dễ thay thế implementation trong unit tests (mock)
- Tăng tính modular của ứng dụng
Action Injection với [FromServices]
Khi nào dùng
Action injection hữu ích khi service chỉ cần cho một action duy nhất, không cần dùng ở nhiều action.So sánh Constructor vs Action Injection
| Tiêu chí | Constructor Injection | Action Injection |
|---|---|---|
| Phạm vi | Tất cả actions trong controller | Chỉ action được chỉ định |
| Tái sử dụng | ✅ Cao | ❌ Thấp |
| Đăng ký | Một lần | Mỗi action |
| Dùng khi | Nhiều actions cần service | Chỉ một action cần service |
Keyed Services với [FromKeyedServices]
Giới thiệu
ASP.NET Core hỗ trợ keyed services — cho phép đăng ký nhiều implementations của cùng một interface với keys khác nhau.Đăng ký Keyed Services
Định nghĩa Interface và Implementations
Sử dụng trong Controller
Truy cập Settings với Options Pattern
Pattern đề xuất
Truy cập app settings từ controller là pattern phổ biến. Options Pattern là cách tiếp cận được ưu tiên thay vì trực tiếp injectIConfiguration.
Bước 1: Tạo Settings Class
Bước 2: Đăng ký Configuration
Bước 3: Cấu hình đọc từ JSON file
Bước 4: Sử dụng trong Controller
Controllers as Services
Mặc định
Theo mặc định, ASP.NET Core không đăng ký controllers như services trong DI container. Runtime dùngDefaultControllerActivator để tạo controller instances và resolve services từ DI container cho constructor parameters.
Kích hoạt Controllers as Services
Lợi ích
| Lợi ích | Mô tả |
|---|---|
| Custom IControllerActivator | Intercept việc tạo controller |
| Lifetime Management | Dùng bất kỳ DI lifetime nào cho controllers |
| Multi-constructor | DI container chọn constructor phù hợp |
Lưu ý: Cấu hìnhApplicationPartManagertrước khi gọiAddControllersAsServices. Xem thêm: Share controllers, views, Razor Pages với Application Parts.