dependenciesnestjscircular-dependency

Nest can't resolve dependencies while all seems right


I was working on a large-scale project where I encountered a (circular?) dependency issue that seemed impossible to resolve, even though all dependencies were properly managed according to NestJS documentation. To better understand the problem and make it easier for others to assist, I created a smaller and isolated project that reproduces the issue.

The raised exception:

[Nest] 46638  - 04/12/2024, 12:20:56   ERROR [ExceptionHandler] Nest can't resolve dependencies of the AuthService (UsersService, ?). Please make sure that the argument dependency at index [1] is available in the AuthModule context.

Potential solutions:
- Is AuthModule a valid NestJS module?
- If dependency is a provider, is it part of the current AuthModule?
- If dependency is exported from a separate @Module, is that module imported within AuthModule?
  @Module({
    imports: [ /* the Module containing dependency */ ]
  })

Here’s what I’ve done so far:

To help you debug it, I created a StackBlitz project.

In addition, when a NestJS project grows to a modestly large size, it happens that some modules have to start using forwardRef(() => Module) in the "imports" section, even if there is no reference to the "calling" module in the imported module (Module).

These are behaviors that I can't explain too much, except by imagining that circular dependency could raise at nested levels, like in the following example (I just tried it and it confirms my theory):

@Module({imports: [ModuleB]})
export class ModuleA {}

@Module({imports: [ModuleC]})
export class ModuleB {}

@Module({imports: [ModuleA]})
export class ModuleC {}

You can find the related code in the nested-circular-dep branch of the same above-mentioned project.

Thank you in advance for your help!

EDIT:

While debugging, I discovered a strange behaviour (main branch): In UsersModule (src/users/users.module.ts) if I move

import { AuthModule } from 'src/auth/auth.module';

on top of

import { CouponsModule } from 'src/coupons/coupons.module';

the application works properly. Could this be related to the Circular file import, as explained in the Common errors section of the official documentation?


Solution

  • Your CreatorService injects the UsersService which injects the AuthService which injects the CouponsService which injects the CreatorService creating the full circular chain that is not yet fully decorated with forwardRefs. There's probably other examples of this in your application, I think I saw that MediaService and PricesService are also both in CreatorService and both use UsersService so you'll probably need forwardRefs there as well.