Search

NestJS 의존성 주입 순환 참조 오류

생성일
2025/01/16 06:44
태그
NestJS
날짜
상위 항목
하위 항목

개요

NestJS는 강력한 의존성 주입 기능을 강제하고 있어 모든 모듈에 대해 관계를 입력해두어야만 필요한 모듈 내의 함수를 사용 할 수 있게 된다. 아래와 같이 순환 참조되는 문제를 해결하라는 에러메세지를 만나게 된다.
Error: Nest cannot create the RepairShopManagementModule instance. The module at index [3] of the RepairShopManagementModule "imports" array is undefined. Potential causes: - A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency - The module at index [3] is of type "undefined". Check your import statements and the type of the module. Scope [AppModule -> CustomerModule -> DispatcherModule -> OrderModule -> ProductModule -> BatteryRushModule -> OrderModule -> ReviewModule -> OrderModule -> VehicleWashStationModule -> ReviewModule -> RepairModule -> RepairShopModule -> CustomerVehicleManagementModule -> CustomerModule -> CouponModule -> CouponTemplateModule -> CouponManagementModule -> OrderModule -> PointModule -> VoucherModule -> PointModule -> ReviewModule -> OnSiteModule]
Plain Text
복사

원인분석

에러 메세지에서 권장하는 방법은 forwardRef() 함수를 사용하여 순환 참조를 무시하라는 방법을 권고한다.
이미 모듈 선언부에 많은 forwardRef()가 있는 것을 확인 할 수 있었는데. 이 방법은 좋은 방법이 아니며,
프레임워크에서 권장하는 의존성 주입에 대한 룰이 깨져 소스가 누더기가 될 수 있다.
또한 추후 MSA 형태로의 전환을 염두에 두고 있다면 순환 참조 구조에선 독립적인 형태로의 변화가 힘들 수 있다.
여기서 몇가지 딜레마에 빠지게 되는데, 무턱대고 forwardRef()로 순환 참조를 만드는 건 문제가 있다라고 보면
과연 어떻게 이 문제를 회피할 수 있을까?
결국 모듈의 의존관계를 철저하게 지켜서 개발할 수 밖에 없다.
의존 문제가 생길때마다 ignore하는 방법으로 진행하다간 커다란 벽에 막혀 생산성 저하라는 큰 문제가 발생하고만다.