Circular Dependency

이연중·2021년 10월 18일
0

NestJS

목록 보기
14/22

순환 종속성은 두 클래스가 서로 의존할 때 발생한다.

순환 종속성은 모듈 간 및 프로바이더 간에 발생할 수 있다.

순환 종속성은 가능한 한 피하는것이 좋다. 하지만, 항상 그렇게 할 수는 없을 것이다.

Nest는 이러한 순환 종속성을 위한 두가지 방법을 제공한다.

  1. Forward Referencing이용
  2. ModuleRef class 이용

Forward Reference


forwardRef() 유틸리티 함수를 사용해 아직 정의되지 않은 클래스를 참조할 수 있다.

다음은 사용예이다. CatsServiceCommenService는 서로 의존하는 관계이다.

@Injectable()
export class CatsService {
  constructor(
    @Inject(forwardRef(() => CommonService))
    private commonService: CommonService,
  ) {}
}
@Injectable()
export class CommonService {
  constructor(
    @Inject(forwardRef(() => CatsService))
    private catsService: CatsService,
  ) {}
}

ModuleRef Class Alterrnative


위 예를 ModuleRef 클래스를 사용하는 방식을 적용하면 아래와 같다.

@Injectable()
export class CatsService implements OnModuleInit{
    private commonService: CommonService
    constructor(private moduleRef: ModuleRef){
    
    onModuleInit(){
        this.commonService= this.moduleRef.get(CommonService)
    }
}
@Injectable()
export class CommonService implements OnModuleInit{
    private catsService: CatsService
    constructor(private moduleRef: ModuleRef){
    
    onModuleInit(){
        this.catsService= this.moduleRef.get(CatsService)
    }
}

Module Forward Reference


모듈간의 순환 종속성 관계 표현은 다음과 같이 하면된다.

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

참고

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

profile
Always's Archives

0개의 댓글