[NestJS 공식문서 정독하기] Fundamentals - Circular dependency

2022. 8. 9. 20:36Web/NestJS

반응형
🔗  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

  • 순환 참조(circular dependency)는 서로 다른 두 클래스가 서로를 의존할 때 생기는 현상임
  • 해당 챕터에서는 provider간의 순환 참조를 해결하는 두 방식인 forward referencingModuleRef 를 소개하고, 모듈간의 순환 참조를 해결하는 방법을 소개함

Forward reference

@Injectable()
export class CatsService {
  constructor(
    @Inject(forwardRef(() => CommonService))
    private commonService: CommonService,
  ) {}
}
@Injectable()
export class CommonService {
  constructor(
    @Inject(forwardRef(() => CatsService))
    private catsService: CatsService,
  ) {}
}
  • forward reference 는 아직 정의되지 않은 클래스를 forwardRef() 유틸리티 함수로 참조하는 방식임
  • 양쪽 모두에서 @Inject()forwardRef() 를 사용해서 순환 참조를 해결할 수 있음
  • 인스턴스화 시점은 불확실하기 때문에 먼저 호출되는 생성자에 의존하지 않도록 코드를 짜야함

ModuleRef class alternative

  • forwardRef() 의 대체재로 ModuleRef 클래스를 사용해서 한쪽에서 provider를 받아오도록 할 수 있음
  • 여기에서 ModuleRef 에 대해 더 자세히 알 수 있음

Module forward reference

@Module({
  imports: [forwardRef(() => CatsModule)],
})
export class CommonModule {}
  • 모듈간의 순환 참조를 해결하기 위해서는 똑같은 forwardRef() 유틸리티 함수를 양쪽 모듈에서 사용하면 됨
반응형