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ễ testdễ 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


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 inject IConfiguration.

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ùng DefaultControllerActivator để tạo controller instances và resolve services từ DI container cho constructor parameters.

Kích hoạt Controllers as Services

Lợi ích

Lưu ý: Cấu hình ApplicationPartManager trước khi gọi AddControllersAsServices. Xem thêm: Share controllers, views, Razor Pages với Application Parts.

So sánh các cách Injection


Tài liệu tham khảo