Junior #di#ioc#injectable
Dependency Injection và IoC container trong NestJS hoạt động ra sao?
⚡ Trả lời nhanh
Nest có IoC container: lúc bootstrap nó đọc metadata kiểu của constructor (emitDecoratorMetadata), dựng dependency graph, tạo instance (singleton mặc định) và inject vào class cần. Class không tự new dependency, nên dễ mock và thay thế khi test.
@Injectable()
export class UsersService {
constructor(private readonly repo: UsersRepository) {} // Nest resolve theo type
}
- Token mặc định là class; Nest lấy kiểu tham số từ metadata do TypeScript phát ra.
- Với interface (không tồn tại lúc runtime) phải dùng token riêng và
@Inject('TOKEN'). - Provider phải được đăng ký trong
providerscủa một module.