순환 종속성 (forwardRef)

손연주·2022년 5월 9일
1

error message

ERROR [ExceptionHandler] A circular dependency has been detected. Please, make sure that each side of a bidirectional relationships are decorated with "forwardRef()".
Error: A circular dependency has been detected. Please, make sure that each side of a bidirectional relationships are decorated with "forwardRef()".

정산 관련 로직을 작성하는 csv.service.ts 에서 유저의 정보를 가져오는 함수가 필요한데, 그 함수는 이미 만들어져 있었다. 따라서 DI를 통해 해당 함수를 import 해와야 했는데 위와 같은 오류가 났다.

해결 방법

이러한 오류가 왜 나는지는 Nest 공식 문서(순환 종속성)를 참고하자. 문서에 따르면 순환 종속성은 두 클래스가 서로 종속될 때 발생한다고 한다. 예를 들어 클래스 A에는 클래스 B가 필요하고 클래스 B에도 클래스 A가 필요할 때를 말하는 것이다.

forwardRef is used to resolve circular dependency.

service.ts

@Injectable()
export class ExcelService {
  constructor(
    @Inject(forwardRef(() => UsersService)) // forwardRef 이용
    private userService: UsersService,
  ) {}
  
  functionName ...

profit.module.ts

@Module({
  imports: [
    ...
    forwardRef(() => UsersModule),
  ],
  providers: [
    ProfitService,
    ExcelService,
    { provide: 'CustomProfitRepository', useClass: DefaultProfitReposiotry },
  ],
  exports: [ProfitService, ExcelService],
})
export class ProfitModule {}

정리

profit 모듈에서 user 모듈을 forwardRef로 import 한 뒤 함수가 필요한 profit service에서 forwardRef로 userService를 Inject 해주면 된다.

profile
할 수 있다는 생각이 정말 나를 할 수 있게 만들어준다.

2개의 댓글

comment-user-thumbnail
2022년 5월 10일

nest 공식 문서도 해석해서 관련 문서로 달면 넘나 좋을것 같아요!!

1개의 답글