Dependency Injection (DI) là kỹ thuật chuyển các đối tượng phụ thuộc (coupled) thành độc lập (decoupled) bằng cách cung cấp phụ thuộc từ bên ngoài thay vì tạo mới bên trong.
Interface Injection (Interface-based Injection)
Khác với Setter Injection dùng property thông thường, Interface Injection yêu cầu lớp consumer triển khai một interface setter chuyên biệt để nhận dependency.
Ví dụ hoàn chỉnh
// 1. Interface dịch vụ
public interface IService
{
string ServiceMethod();
}
// 2. Triển khai cụ thể
public class ClaimService : IService
{
public string ServiceMethod() => "ClaimService is running";
}
public class AdjudicationService : IService
{
public string ServiceMethod() => "AdjudicationService is running";
}
// 3. Interface setter chuyên biệt
public interface ISetService
{
void SetService(IService service);
}
// 4. Consumer triển khai interface setter
public class BusinessLogic : ISetService
{
private IService _service;
public void SetService(IService service)
{
_service = service;
Console.WriteLine($"Interface Injection => Current Service: {_service.ServiceMethod()}");
}
}
// 5. Sử dụng (Composition Root)
class Program
{
static void Main()
{
var logic = new BusinessLogic();
logic.SetService(new ClaimService()); // Inject ClaimService
logic.SetService(new AdjudicationService()); // Thay bằng AdjudicationService
Console.ReadLine();
}
}
Đặc điểm
- Tách biệt rõ ràng: Consumer không biết concrete type, chỉ biết
IService. - Setter tường minh: Interface
ISetServiceép buộc consumer phải cung cấp phương thức inject. - Linh hoạt: Dễ dàng thay đổi implementation tại runtime.
So sánh nhanh các loại DI
| Loại | Cách inject | Đặc điểm |
|---|---|---|
| Constructor Injection | Qua constructor | Bắt buộc, bất biến, khuyến nghị nhất |
| Setter/Property Injection | Qua property public | Tùy chọn, có thể thay đổi sau khởi tạo |
| Interface Injection | Qua interface setter | Tường minh, ít dùng hơn |
| Service Locator | Truy vấn từ container | Anti-pattern theo quan điểm nhiều người |
Khuyến nghị: Trong ứng dụng hiện đại, hãy ưu tiên Constructor Injection kết hợp với DI Container (Microsoft.Extensions.DependencyInjection, Autofac, v.v.). Interface Injection chủ yếu dùng trong các framework cũ hoặc kịch bản đặc biệt.