You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS项目使用forwardRef仍存在循环依赖问题求助

NestJS 循环依赖问题:AuthService 导入 UserService 失败

尝试在AuthService中导入UserModule导出的UserService时遇到循环依赖,已使用forwardRef(() => UserService)但未解决,错误信息如下:

ERROR [ExceptionHandler] A circular dependency has been detected inside AuthModule. Please, make sure that each side of a bidirectional relationships are decorated with "forwardRef()". Note that circular relationships between custom providers (e.g., factories) are not supported since functions cannot be called more than once.

AuthService 代码

import { forwardRef, Inject, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { User } from 'src/user/entity/user.entity';
import { LoginDto } from './dto/login.dto';
import * as bcrypt from 'bcrypt';
import { UserService } from 'src/user/user.service';

@Injectable()
export class AuthService {

    constructor(
        private jwtService: JwtService,
        @Inject(forwardRef(() => UserService))
        private userService: UserService,
    ) {}

    async validateAdmin(email: string, password: string): Promise<User | null> {
        const user = await this.userService.findOneByEmail(email);
        if (user && await bcrypt.compare(password, user.password)) {
            return user;
        } 
        return null;
    }


    async login(loginDto: LoginDto) {
        const user = await this.validateAdmin(loginDto.email, loginDto.password);
        if (!user) {
            throw new Error('Invalid credentials');
        }
        const payload = { email: user.email, role: user.role };
        return {
          access_token: this.jwtService.sign(payload),
        };
    }
}

AuthModule 代码

import {  Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy } from './jwt.strategy';

@Module({
    imports: [
        JwtModule.register({
            secret: process.env.JWT_SECRET_KEY,
            signOptions: { expiresIn: '1h' },
        }),
    ],
    controllers: [AuthController],
    providers: [AuthService, , JwtStrategy],
})
export class AuthModule {}

解决步骤

循环依赖需要双向配置forwardRef,你仅在AuthService中配置了单方向,需补充以下操作:

1. 修复AuthModule语法错误

providers数组中多了一个多余逗号,修改为:

providers: [AuthService, JwtStrategy],

2. 在UserModule中导入AuthModule时使用forwardRef

如果UserModule依赖AuthModule,需用forwardRef包裹导入:

import { forwardRef, Module } from '@nestjs/common';
import { AuthModule } from 'src/auth/auth.module';

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

3. 在UserService中注入AuthService时使用forwardRef

如果UserService的构造函数中也注入了AuthService,同样需要用forwardRef:

import { forwardRef, Inject, Injectable } from '@nestjs/common';
import { AuthService } from 'src/auth/auth.service';

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

4. 确保AuthModule导入UserModule时用forwardRef

若AuthModule需要导入UserModule,也要用forwardRef包裹:

import { forwardRef, Module } from '@nestjs/common';
import { UserModule } from 'src/user/user.module';

@Module({
  imports: [
    JwtModule.register({...}),
    forwardRef(() => UserModule)
  ],
  controllers: [AuthController],
  providers: [AuthService, JwtStrategy],
  exports: [AuthService] // 若UserModule需要使用AuthService,需导出
})
export class AuthModule {}

内容的提问来源于stack exchange,提问作者mahdi nurazaman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 12:27:20