Search code examples
dependency-injectionnestjsinversion-of-control

Object gotten from the NestFactory has all the internal dependencies as undefined - NestJS


I get an object from NestFactory and then I call a function. There is another class injected inside service class. All the dependencies inside the service are not accessible.

const FASTIFY = new FastifyAdapter();
const app = await NestFactory.create<NestFastifyApplication>(AppModule, FASTIFY, {
        bufferLogs: true, // do wait till LoggerService is available
});
const service = app.get<ServiceClass>(ServiceClass);  // service object is obtained from container
console.log(service.anotherRepository); // repository and injected objects are undefined.

Service object is obtained from container and then I can see the code goes into service class but all the dependencies defined inside the service class are undefined.

I have set the scope of all of them to DEFAULT.

@Injectable({ scope: Scope.DEFAULT })

Solution

  • Even if the classes are created with scope: Scope.REQUEST. You can still get the objects using

    const serviceClass = await app.resolve<ServiceClass>(ServiceClass);
    

    This has been fixed in the newer versions.