Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Dependency Injection (Tiêm phụ thuộc) trong C#

Dependency Injection cho phép phát triển loosely coupled code (dễ maintain, reuse).

Các loại DI:

Constructor Injection

Dùng parameter constructor để inject dependencies. Hữu ích khi class cần 1+ dependencies.

Setter Injection

Kiểm tra null trước khi dùng. Cho phép tạo resource/service khi cần.

Method Injection

Inject dependency vào một method đơn lẻ, chỉ method đó sử dụng.