# Circular dependency

## Circular dependency

순환 종속성은 예를 들어 클래스 A에 클래스 B가 필요하고 클래스 B에 클래스 A가 필요할 때 발생합니다. Nest는 공급자와 모듈간에 **순환 종속성**을 만들 수 있지만 가능할 때마다 피하는 것이 좋습니다. 때때로 이런 종류의 관계를 피하는 것이 매우 어렵기 때문에 우리는이 문제를 해결할 수 있는 방법을 제공했습니다.

## Forward reference

**전달 참조**는 지금까지 정의되지 않은 참조를 Nest가 참조할 수 있도록 합니다. `CatsService`와 `CommonService`가 서로 의존하는 경우, 관계의 양쪽 모두 `@Inject()`와 `forwardRef()`유틸리티를 사용해야 합니다. 사용할 수 없습니다. 다음 스니펫을 보자.

```typescript
@@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`로 똑같이 해봅시다 :

```typescript
@@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()`유틸리티를 사용해야 합니다.

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

## Module reference

Nest는 모든 컴포넌트에 간단히 주입할 수있는 `ModuleRef` 클래스를 제공합니다.

```typescript
@@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() 메서드가 있습니다. 또한 엄격하지 않은 모드로 전환하여 전체 응용 프로그램중에서 기존 공급자를 선택할 수 있습니다.

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jakekwak.gitbook.io/nestjs/fundamentals/circular-dependency.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
