Injection Scopes trong NestJS

Injection Scopes xác định vòng đời và số lượng instances của một provider. NestJS cung cấp ba scope khác nhau, mỗi cái có use cases và performance implications khác nhau. Hiểu rõ scopes là quan trọng để tối ưu hóa performance và tránh memory leaks.

Các Loại Scopes

1. SINGLETON (Default)

Một instance duy nhất được tạo một lầnchia sẻ cho toàn bộ ứng dụng:
Đặc điểm:
  • ✅ Best performance (instance được reuse)
  • ✅ Memory efficient
  • ❌ Chia sẻ state giữa requests
  • ❌ Không thread-safe (trong context của multiple requests)
Khi sử dụng:
  • Stateless services (DatabaseService, ConfigService)
  • Utilities và helpers
  • Heavy initialization services

2. REQUEST

Một instance mới được tạo cho mỗi HTTP request:
Đặc điểm:
  • ✅ Isolation giữa requests
  • ✅ Request-scoped state an toàn
  • ❌ Tốn memory hơn
  • ❌ Performance overhead từ tạo instances mới
Khi sử dụng:
  • Request-scoped utilities
  • Temporary data holders
  • Request context managers
  • Session-specific services

3. TRANSIENT

Một instance mới được tạo mỗi khi được inject:
Đặc điểm:
  • ✅ Hoàn toàn isolated instances
  • ✅ Không chia sẻ state
  • ❌ Tốn memory nhiều nhất
  • ❌ Performance worst case
Khi sử dụng:
  • Hiếm khi sử dụng
  • Khi bạn cần hoàn toàn isolated state
  • Một số specialized use cases

Scope Comparison

Ví Dụ Thực Tế

1. Request Context Service (REQUEST scoped)

2. Database Transaction (REQUEST scoped)

3. Logger with Request Tracking (REQUEST scoped)

4. Data Loader (REQUEST scoped)

5. Audit Logger (REQUEST scoped)

6. Session Service (REQUEST scoped)

7. Performance Monitoring (REQUEST scoped)

8. Switching Scopes Dynamically

Scope Rules and Constraints

Scope Compatibility

Best Practices

1. Use SINGLETON by Default

2. Use REQUEST for Per-Request State

3. Avoid TRANSIENT

4. Document Scope Selection

5. Be Aware of Scope Injection Rules

Kết Luận

Injection Scopes là fundamental concept trong NestJS: SINGLETON:
  • Best performance
  • Ideal cho stateless services
  • Default choice
REQUEST:
  • Per-request isolation
  • Ideal cho request-specific state
  • Small performance overhead
TRANSIENT:
  • Rarely used
  • Each injection gets new instance
  • High memory overhead
Key Takeaways:
  • Default to SINGLETON
  • Use REQUEST cho per-request state
  • Avoid TRANSIENT
  • Be aware of scope compatibility rules
  • Request-scoped services cannot be injected into singletons
Sử dụng scopes đúng cách là crucial cho xây dựng efficient, safe, và scalable NestJS applications!