원문: https://docs.nestjs.com/fundamentals/circular-dependency
Circular dependency
A circular dependency occurs when two classes depend on each other. For example, class A needs class B, and class B also needs class A. Circular dependencies can arise in Nest between modules and between providers.
순환 종속성은 두 클래스가 서로 종속될때 발생한다. 예를 들어, 클래스A가 클래스 B를 필요로하고, 또한 클래스B가 클래스 A를 필요로 하는 경우이다. 순환 종속성은 모듈과 프로바이더 사이에서 일어날 수 있다.
While circular dependencies should be avoided where possible, you can't always do so. In such cases, Nest enables resolving circular dependencies between providers in two ways. In this chapter, we describe using forward referencing as one technique, and using the ModuleRef class to retrieve a provider instance from the DI container as another.
순환 종속성은 가능한 피해야하지만, 항상 그럴수만은 없다. 이때, Nest는 두가지 방법으로 프로바이더 사이의 순환 종속성을 해결할 수 있게한다. 이 챕터에선 forward referencing을 사용하는 방법과 ModuleRef을 사용해 DI container에서 프로바이더 인스턴스를 검색하는 방법을 설명할 것이다.
*retrieve: 되찾아오다, 회수하다, 검색하다
We also describe resolving circular dependencies between modules.
또한 모듈간의 순환 종속성을 해결하는 방법을 설명할 것이다.
A circular dependency might also be caused when using "barrel files"/index.ts files to group imports. Barrel files should be omitted when it comes to module/provider classes. For example, barrel files should not be used when importing files within the same directory as the barrel file, i.e. cats/cats.controller should not import cats to import the cats/cats.service file. For more details please also see this github issue.
순환 종속성은 "barrel files"/index.ts으로 그룹 임포팅할때에도 발생할 수 있다. 모듈/프로바이더 클래스들로 가져와질때 배럴 파일들이 빠뜨려질 수 있다. 예를 들어, 배럴 파일들이 같은 디렉토리 파일안에서 임포트될때 배럴 파일들이 사용되지 않을 수 있다. cats/cats.controller는 cats/cats.service파일을 임포트하기 위해선 cats를 임포트해선 안된다. 더 자세한 내용은 깃헙 이슈 참고.
Forward reference
A forward reference allows Nest to reference classes which aren't yet defined using the forwardRef() utility function. For example, if CatsService and CommonService depend on each other, both sides of the relationship can use @Inject() and the forwardRef() utility to resolve the circular dependency. Otherwise Nest won't instantiate them because all of the essential metadata won't be available. Here's an example:
forward reference은 Nest가 유틸리티 함수 forwardRef()을 사용해 아직 정의되지 않은 클래스들을 참조할 수 있게한다. 예를 들어, 만약 CatsService와 CommonService이 서로를 의존한다 했을때, 두 관계는 @Inject()와 forwardRef() 유틸리티를 사용해 순환 종속성을 해결할 수 있다. 그렇지 않으면, 필수 메타데이터가 유효하지 않기 때문에, Nest는 두 서비스의 인스턴스를 생성하지 않는다. 한가지 예시를 보자.
@Injectable()
export class CatsService {
constructor(
@Inject(forwardRef(() => CommonService))
private commonService: CommonService,
) {}
}
HINT The forwardRef() function is imported from the @nestjs/commonpackage.
힌트 forwardRef() 함수는 @nestjs/common 패키지에서 임포트한다.
That covers one side of the relationship. Now let's do the same with CommonService:
이것은 한쪽의 관계를 해결해준다. 이제, CommonService에도 같은 방식으로 커버해보자.
(*CommonService ↔ CatService인데, CatService쪽만 forwardRef()를 사용해 커버했다는 뜻)
@Injectable()
export class CommonService {
constructor(
@Inject(forwardRef(() => CatsService))
private catsService: CatsService,
) {}
}
The order of instantiation is indeterminate. Make sure your code does not depend on which constructor is called first. Having circular dependencies depend on providers with Scope.REQUEST can lead to undefined dependencies. More information available here
인스턴스화의 순서는 쉽게 가늠할 수 없다. 코드가 먼저 호출되는 생성자에 따라 달라지지 않는지 확인해야한다. Scope.REQUEST 와 프로바이더에 의해 순환 종속성을 갖는것은 undefined dependencies로 이끈다. 자세한 정보는 여기로 (?)
ModuleRef class alternative
An alternative to using forwardRef() is to refactor your code and use the ModuleRef class to retrieve a provider on one side of the (otherwise) circular relationship. Learn more about the ModuleRef utility class here.
forwardRef()을 사용하는 것의을 대신해, 코드를 리펙터링하거나 ModuleRef클래스를 사용해 순환 관계의 한쪽(다른쪽) 프로바이더를 검색할 수 있다.
Module forward reference
In order to resolve circular dependencies between modules, use the same forwardRef() utility function on both sides of the modules association. For example:
두 모듈간의 순환 종속성을 해결하기 위해, 같은 forwardRef()유틸리티 함수를 양쪽 모듈 연관성에 사용한다. 예시:
@Module({
imports: [forwardRef(() => CatsModule)],
})
export class CommonModule {}
'Dev > 코딩공부 이모저모' 카테고리의 다른 글
server) 호랑이는 죽어서 가죽을 남기고, 개발자는 죽어서 로그를 남긴다. (0) | 2022.03.01 |
---|---|
VScode ) Beautify 설정 (0) | 2022.01.15 |
Api 문서 자동화에 대한 개인적인 노력과 후기... (0) | 2021.12.26 |
NCP) nCloud 네이버 API Signature Key 생성 (0) | 2021.10.09 |
Server ) RESTful API, 자주 사용하는 Status code 정리 및 예시 (0) | 2021.10.04 |