본문 바로가기
개발/NestJS

[NestJs] 순환 종속성(Circular Dependency) 에러

by coking 2022. 10. 23.
A circular dependency between modules. Use forwardRef() to avoid it. 
Read more: https://docs.nestjs.com/fundamentals/circular-dependency

위 에러코드에 url은 순환 종속성을 해결하게 해주는 방법을 제공하는 NestJs 공식 url이다.

 

개발하면서 서버를 띄우면 종종 이런 에러가 발생하곤 한다. 과연 Circular Dependency라고 하는 이 녀석은 무엇일까? 

바로 순환 종속성이라고 불리며 예를 들어 클래스 A에 클래스 B가 필요하고 클래스 B에 클래스 A가 필요하면 발생하며 

클래스 A <-> 클래스 B 이런 관계를 형성하고 있다고 보면 된다. 

결국 A가 초기화되기도 전에 B가 A를 의존하기 때문에 서로 에러를 발생하게 된다.

될 수 있으면 이런 관계를 피하는 게 가장 좋으나 불가피하게 피할 수 없을 때 문제를 해결하는 방법을 제공하겠다. 

 

Forward reference(전달 참조)

전달 참조는 지금까지 정의되지 않은 참조를 Nest가 참조할 수 있도록 한다. 

@Module({
	imports: [forwardRef(() => TestModule)],
})
export class UserModule {}

이렇게 문제가 발생한 부분에서 전달 참조를 사용해서 해결하면 된다.

 

참조 문서 

https://docs.nestjs.com/fundamentals/circular-dependency

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reac

docs.nestjs.com

 

 

댓글