Jango
Jango

Reputation: 155

NestJs dependency injection with task scheduling is not working

I am trying to implement task scheduling as described in Nest documentation, but there is no example with dependency injection for a service that uses scheduling. What I want is to use injected services in recurring tasks, but when I do something like this:

@Injectable()
export class MyWorkerService {

    constructor(private readonly injectedService: MyInjectedService) {}

    @Timeout(5000)
    async doSomething():  { 
     console.log(this.injectedService); // undefined
     this.injectedService.doStuff(); // TypeError: cannot read property 'doStuff' of undefined
    }
}

...dependency injection just does not work. Both services are registered as providers in the same module.

Why would this happen? How else can I access my other services from scheduled methods?

Upvotes: 2

Views: 2650

Answers (1)

Jango
Jango

Reputation: 155

Here I am answering my own question 2 hours later :)

So basically one of the services that I injected into service that I injected into my scheduled service had REQUEST scope:

@Injectable({ scope: Scope.REQUEST })

After removing it from injected service constructor dependency injection began working as expected.

Upvotes: 7

Related Questions