MeWrite Docs

NestJS: Nest can't resolve dependencies

NestJSで依存性注入が解決できない場合のエラー原因と解決策

概要

NestJSのDIコンテナが必要な依存関係を解決できない場合に発生するエラーです。

エラーメッセージ

``` Nest can’t resolve dependencies of the UserService (?). Please make sure that the argument UserRepository at index [0] is available in the UserModule context. ```

原因

  1. モジュールへの未登録: providersに追加されていない
  2. 循環依存: 2つのサービスが互いに依存
  3. スコープの問題: REQUEST scopeとSINGLETONの混在
  4. インポート忘れ: 外部モジュールのimports漏れ

解決策

1. providersに登録

```typescript // user.module.ts @Module({ imports: [TypeOrmModule.forFeature([User])], providers: [UserService, UserRepository], // 両方登録 exports: [UserService], }) export class UserModule {} ```

2. 循環依存を解決

```typescript // forwardRef を使用 @Injectable() export class UserService { constructor( @Inject(forwardRef(() => OrderService)) private orderService: OrderService, ) {} }

// モジュールレベルでも @Module({ imports: [forwardRef(() => OrderModule)], }) export class UserModule {} ```

3. モジュールをインポート

```typescript // app.module.ts @Module({ imports: [ TypeOrmModule.forRoot(config), UserModule, OrderModule, ], }) export class AppModule {} ```

4. カスタムプロバイダー

```typescript @Module({ providers: [ { provide: ‘CONFIG’, useValue: { apiKey: ‘xxx’ }, }, { provide: UserService, useFactory: (config) => new UserService(config), inject: [‘CONFIG’], }, ], }) export class UserModule {} ```

よくある間違い

  • @Injectable() デコレータの付け忘れ
  • exportsに追加せず他モジュールで使おうとする
  • グローバルモジュールの設定漏れ

関連エラー

関連エラー

Node.js の他のエラー

最終更新: 2025-12-11