'How to resolve a circular dependency in nest js?

I have my app.module that imports UserModule and AuthModule.

@Module({
  imports: [UserModule, AuthModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

This is how my AuthModule looks:

@Module({
  imports: [forwardRef(() => UserModule)],
  controllers: [AuthController],
  providers: [AuthService, UserService],
  exports: [AuthModule],
})
export class AuthModule {}

And UserModule:

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  controllers: [UserController],
  providers: [UserService],
})
export class UserModule {}

I inject userService in AuthService. If i delete AuthModule from AppModule, the dependency disapears, so, the problem is maybe somewhere there.



Solution 1:[1]

First of all, configure the user module and auth module so that they can refer to each other.

@Module({
  imports: [
    forwardRef(() => UserModule),
  ],
  exports: [AuthService],
  controllers: [AuthController],
  providers: [AuthService],
})
export class AuthModule {}

@Module({
  imports: [
    forwardRef(() => AuthModule),
  ],
  exports: [UserService],
  controllers: [UserController],
  providers: [UserService],
})
export class UserModule {}

In this situation, two different services that perform dependency injection must also be configured so that cross-references are possible.

@Injectable()
export class UserService {
  constructor(
    @Inject(forwardRef(() => AuthService))
  )
}

@Injectable()
export class AuthService {
  constructor(
    @Inject(forwardRef(() => UserService))
  )
}

Please try and comment if it doesn't work.

Solution 2:[2]

If you strongly believe that circular dependency is a false positive, check that if you happen to have a JSON file with the same name as a .ts file

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 blue-hope
Solution 2 glinda93