最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

onModuleInit Not Executing Due to Circular Dependency in NestJS with forwardRef() - Stack Overflow

programmeradmin2浏览0评论

I'm facing an issue in my NestJS application where the onModuleInit lifecycle hook is not being executed in one of my services (JobsService) when a circular dependency is involved.

Specifically:

  • JobsService depends on ServiceAppointmentsService.

  • ServiceAppointmentsService depends on JobsService.

  • I'm using forwardRef() to resolve the circular dependency.

  • However, the onModuleInit() hook in JobsService does not run, and I can't restore pending jobs on startup as expected.

What I’ve Tried

  1. Used forwardRef() in both services to resolve the circular dependency.

  2. Wrapped the onModuleInit() logic in a try-catch block to catch errors.

  3. Added console.log() statements for debugging, but execution never reaches onModuleInit().

JobsService

@Injectable()
export class JobsService implements OnModuleInit {
  constructor(
    @InjectRepository(Job)
    private readonly jobRepo: Repository<Job>,

    @Inject(WINSTON_MODULE_PROVIDER)
    private readonly logger: Logger,

    private readonly schedulerRegistry: SchedulerRegistry,

    @Inject(forwardRef(() => ServiceAppointmentsService))
    private readonly serviceAppointmentsService: ServiceAppointmentsService, // Circular dependency
  ) {}

  async onModuleInit(): Promise<void> {
    try {
      console.log("Initializing JobsService...");
      const jobs: Job[] = await this.getPendingJobs();
      // Logic to restore pending jobs
    } catch (err: any) {
      this.logger.error(`Error restoring pending jobs: ${err.message || err}`);
    }
  }

  async getPendingJobs(): Promise<Job[]> {
    return this.jobRepo.find({ where: { status: 'pending' } });
  }
}

ServiceAppointmentsService

@Injectable()
export class ServiceAppointmentsService {
  constructor(
    @Inject(forwardRef(() => JobsService))
    private readonly jobService: JobsService, // Circular dependency
  ) {}

  async createAppointment() {
    // Logic to create appointments
  }
}

Issue

When I include both dependencies in the services using forwardRef(), the onModuleInit() hook in JobsService is not executed at all. This prevents me from initializing or restoring pending jobs on application startup.

What I’ve Tried to Fix It

  • Ensured both services use forwardRef() → The problem persists.

  • Checked if onModuleInit() runs at all → It does not get triggered.

  • Added debug logs (console.log()) → No logs appear from onModuleInit().

Possible Causes

  • Does onModuleInit() not execute when circular dependencies exist?

  • Could NestJS be skipping the lifecycle hook due to how dependencies are resolved?

Expected Outcome

  • The onModuleInit() hook in JobsService should execute normally.

  • Pending jobs should be restored during the application startup phase.

How can I ensure onModuleInit() runs correctly despite the circular dependency?

发布评论

评论列表(0)

  1. 暂无评论