Circular dependency xảy ra khi OrderModule import PaymentModule và ngược lại: mỗi bên chờ bên kia khởi tạo xong, DI container rơi vào deadlock. Triệu chứng điển hình là Nest cannot create the X instance. The module at index [n] of the X 'imports' array is undefined — vì tại thời điểm đọc file, một bên vẫn chưa được export.
Cách xử lý bằng forwardRef — phải khai báo ở cả hai phía:
@Module({ imports: [forwardRef(() => PaymentModule)] })
export class OrderModule {}
@Module({ imports: [forwardRef(() => OrderModule)] })
export class PaymentModule {}Ở cấp provider cũng tương tự: @Inject(forwardRef(() => PaymentService)). forwardRef hoãn việc resolve tới khi mọi module đã nạp xong, phá vỡ vòng chờ.
Vì sao nên coi là phương án cuối: vòng phụ thuộc là dấu hiệu ranh giới module đặt sai. Cách gỡ tốt hơn là tách phần dùng chung ra module thứ ba mà cả hai cùng import, hoặc đảo chiều một hướng bằng event (EventEmitter2) để PaymentModule chỉ phát sự kiện thay vì gọi trực tiếp OrderService. forwardRef cũng không hoạt động với circular dependency ở cấp file TypeScript thuần (import vòng giữa hai file), và làm việc debug thứ tự khởi tạo khó hơn.