Circular dependency

Circular dependency

μˆœν™˜ 쒅속성은 예λ₯Ό λ“€μ–΄ 클래슀 A에 클래슀 Bκ°€ ν•„μš”ν•˜κ³  클래슀 B에 클래슀 Aκ°€ ν•„μš”ν•  λ•Œ λ°œμƒν•©λ‹ˆλ‹€. NestλŠ” κ³΅κΈ‰μžμ™€ λͺ¨λ“ˆκ°„에 μˆœν™˜ 쒅속성을 λ§Œλ“€ 수 μžˆμ§€λ§Œ κ°€λŠ₯ν•  λ•Œλ§ˆλ‹€ ν”Όν•˜λŠ” 것이 μ’‹μŠ΅λ‹ˆλ‹€. λ•Œλ•Œλ‘œ 이런 μ’…λ₯˜μ˜ 관계λ₯Ό ν”Όν•˜λŠ” 것이 맀우 μ–΄λ ΅κΈ° λ•Œλ¬Έμ— μš°λ¦¬λŠ”μ΄ 문제λ₯Ό ν•΄κ²°ν•  수 μžˆλŠ” 방법을 μ œκ³΅ν–ˆμŠ΅λ‹ˆλ‹€.

Forward reference

전달 μ°Έμ‘°λŠ” μ§€κΈˆκΉŒμ§€ μ •μ˜λ˜μ§€ μ•Šμ€ μ°Έμ‘°λ₯Ό Nestκ°€ μ°Έμ‘°ν•  수 μžˆλ„λ‘ ν•©λ‹ˆλ‹€. CatsService와 CommonServiceκ°€ μ„œλ‘œ μ˜μ‘΄ν•˜λŠ” 경우, κ΄€κ³„μ˜ μ–‘μͺ½ λͺ¨λ‘ @Inject()와 forwardRef()μœ ν‹Έλ¦¬ν‹°λ₯Ό μ‚¬μš©ν•΄μ•Ό ν•©λ‹ˆλ‹€. μ‚¬μš©ν•  수 μ—†μŠ΅λ‹ˆλ‹€. λ‹€μŒ μŠ€λ‹ˆνŽ«μ„ 보자.

@@filename(cats.service)
@Injectable()
export class CatsService {
  constructor(
    @Inject(forwardRef(() => CommonService))
    private readonly commonService: CommonService,
  ) {}
}
@@switch
@Injectable()
@Dependencies(forwardRef(() => CommonService))
export class CatsService {
  constructor(commonService) {
    this.commonService = commonService;
  }
}

info 힌트 forwardRef()ν•¨μˆ˜λŠ” @nestjs/common νŒ¨ν‚€μ§€μ—μ„œ κ°€μ Έμ˜΅λ‹ˆλ‹€.

κ΄€κ³„μ˜ 첫 번째 μ‚¬μ΄λ“œκ°€ μžˆμŠ΅λ‹ˆλ‹€. 이제 CommonService둜 λ˜‘κ°™μ΄ ν•΄λ΄…μ‹œλ‹€ :

@@filename(common.service)
@Injectable()
export class CommonService {
  constructor(
    @Inject(forwardRef(() => CatsService))
    private readonly catsService: CatsService,
  ) {}
}
@@switch
@Injectable()
@Dependencies(forwardRef(() => CatsService))
export class CommonService {
  constructor(catsService) {
    this.catsService = catsService;
  }
}

warning κ²½κ³  μ–΄λ–€ μƒμ„±μžκ°€ λ¨Όμ € ν˜ΈμΆœλ˜λŠ”μ§€ 보μž₯ ν•  수 μ—†μŠ΅λ‹ˆλ‹€.

λͺ¨λ“ˆκ°„ μˆœν™˜ 쒅속성을 μƒμ„±ν•˜λ €λ©΄ 두 λͺ¨λ“ˆ μ—°κ²°μ—μ„œ λ™μΌν•œ forwardRef()μœ ν‹Έλ¦¬ν‹°λ₯Ό μ‚¬μš©ν•΄μ•Ό ν•©λ‹ˆλ‹€.

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

Module reference

NestλŠ” λͺ¨λ“  μ»΄ν¬λ„ŒνŠΈμ— κ°„λ‹¨νžˆ μ£Όμž…ν•  μˆ˜μžˆλŠ” ModuleRef 클래슀λ₯Ό μ œκ³΅ν•©λ‹ˆλ‹€.

@@filename(cats.service)
@Injectable()
export class CatsService implements OnModuleInit {
  private service: Service;
  constructor(private readonly moduleRef: ModuleRef) {}

  onModuleInit() {
    this.service = this.moduleRef.get(Service);
  }
}
@@switch
@Injectable()
@Dependencies(ModuleRef)
export class CatsService {
  constructor(moduleRef) {
    this.moduleRef = moduleRef;
  }

  onModuleInit() {
    this.service = this.moduleRef.get(Service);
  }
}

info 힌트 ModuleRef ν΄λž˜μŠ€λŠ”@nestjs/core νŒ¨ν‚€μ§€μ—μ„œ κ°€μ Έμ˜΅λ‹ˆλ‹€.

λͺ¨λ“ˆ μ°Έμ‘°μ—λŠ” ν˜„μž¬ λͺ¨λ“ˆμ—μ„œ μ‚¬μš© κ°€λŠ₯ν•œ κ³΅κΈ‰μžλ₯Ό 검색할 μˆ˜μžˆλŠ” get() λ©”μ„œλ“œκ°€ μžˆμŠ΅λ‹ˆλ‹€. λ˜ν•œ μ—„κ²©ν•˜μ§€ μ•Šμ€ λͺ¨λ“œλ‘œ μ „ν™˜ν•˜μ—¬ 전체 μ‘μš© ν”„λ‘œκ·Έλž¨μ€‘μ—μ„œ κΈ°μ‘΄ κ³΅κΈ‰μžλ₯Ό 선택할 수 μžˆμŠ΅λ‹ˆλ‹€.

this.moduleRef.get(Service, { strict: false });

Last updated

Was this helpful?