Nest can't resolve dependencies of the

Viewed 1446

I'am trying to use AuthService into UsersService and UsersService into AuthService, so this is called "circular dependency". The issue is that "Nest can't resolve dependencies of the AuthService (UserModel, JwtService, ?). Please make sure that the argument dependency at index [2] is available in the AuthModule context."

UsersModule:

@Module({
  imports: [
    MongooseModule.forFeature([
      {
        name: User.name, schema: UserSchema
      }
    ]),
    forwardRef(() => AuthModule),
  ],
  controllers: [UsersController],
  providers: [UsersService], 
  exports: [UsersService]
}) 
export class UsersModule {}enter code here

AuthModule:

@Module({
  imports: [
    MongooseModule.forFeature([{name: User.name, schema: UserSchema}]),
    JwtModule.register({ secret: process.env.JWT_SECRET }),
    forwardRef(() => UsersModule),
  ],
  controllers: [AuthController],
  providers: [AuthService, JwtStrategy],
  exports: [AuthService, JwtModule]
})
export class AuthModule {}

UsersService (works fine):

@Injectable()
export class UsersService {
  constructor(
      @InjectModel(User.name) private userModel: Model<UserDocument>,
      private jwtService: JwtService,
      private authService: AuthService
    ) {}
...

AuthService (where error occurs):

@Injectable()
export class AuthService {
  constructor(
      @InjectModel(User.name) private userModel: Model<UserDocument>, 
      private jwtService: JwtService,
      private userService: UsersService,
    ) {}
...
2 Answers

You've resolved the circular dependency between the modules, but not between the services. Each side of the service needs @Inject(forwardRef(() => InjectedClass)). So your AuthService would use @Inject(forwardRef(() => UserService))

Circular dependencies are bad and trying to get around them using things like forwardRef mentioned in the other answer is not good practice.

Look into other patterns for inter-service communication. Events for example: https://docs.nestjs.com/techniques/events

Related