🔧 Dependency Injection - So Sánh & Demo

Hiểu rõ sự khác biệt giữa Tight Coupling và Dependency Injection

📚 Dependency Injection là gì?

Dependency Injection (DI) là một design pattern quan trọng trong lập trình:

  • Injector: Container chứa các API để tạo và quản lý instances
  • Provider: "Công thức" để Injector biết cách tạo dependency
  • Dependency: Object/service cần được inject vào component

❌ Tight Coupling (Không nên làm)

{{ badExample }}

🚫 Vấn đề:

  • • Khó thay đổi implementation
  • • Không thể test với mock objects
  • • Mỗi component có instance riêng
  • • Vi phạm SOLID principles
  • • Code cứng nhắc, khó maintain

✅ Dependency Injection (Cách đúng)

{{ goodExample }}

✨ Ưu điểm:

  • • Loose coupling giữa các components
  • • Dễ dàng test với mock objects
  • • Share state giữa components
  • • Tuân thủ SOLID principles
  • • Code linh hoạt, dễ maintain

🔄 Provider Override - Thay Đổi Implementation

{{ overrideExample }}

Provider Override cho phép thay đổi implementation mà không cần sửa component code:

  • Development environment: MockCartService
  • Production environment: ApiCartService
  • Testing environment: TestCartService

🎮 Interactive Demo

📝 Hướng dẫn: Nhấn các nút trên và kiểm tra Browser Console (F12 → Console) để xem chi tiết cách DI hoạt động.

🌟 Lợi Ích Của Dependency Injection

🧪

Testability

Dễ dàng mock dependencies trong unit tests, tăng code coverage và reliability.

🔧

Maintainability

Code loose coupling, dễ modify và extend mà không ảnh hưởng các component khác.

🔄

Flexibility

Dễ dàng swap implementations cho different environments (dev, test, prod).

Performance

Singleton pattern giúp share instances, giảm memory usage và tăng performance.

🅰️ Angular DI Features

🎯

Hierarchical Injection

DI system có hierarchy từ root → module → component, cho phép override ở mỗi level.

🏭

Multiple Provider Types

Class, Factory, Value, và Existing providers cho flexibility tối đa.

🔍

Tree-shakable Services

providedIn: 'root' cho phép tree-shaking, chỉ bundle services thực sự được sử dụng.