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 onServiceAppointmentsService
.ServiceAppointmentsService
depends onJobsService
.I'm using
forwardRef()
to resolve the circular dependency.However, the
onModuleInit()
hook inJobsService
does not run, and I can't restore pending jobs on startup as expected.
What I’ve Tried
Used
forwardRef()
in both services to resolve the circular dependency.Wrapped the
onModuleInit()
logic in atry-catch
block to catch errors.Added
console.log()
statements for debugging, but execution never reachesonModuleInit()
.
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 fromonModuleInit()
.
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 inJobsService
should execute normally.Pending jobs should be restored during the application startup phase.
How can I ensure onModuleInit()
runs correctly despite the circular dependency?