When creating an injectable class using ModuleRef.create()
that is transient
it works as expected:
ModuleRef.create()
is calledBut if this class injects another class that is also transient
, then it does not work as expected:
ModuleRef.create()
is called for its parentThis results in errors of undefined.
Minimal repository to reproduce: https://github.com/MickL/nest-di-bug
await this.moduleRef.create(CatService); // Creates `CatService` but not `CatPetService`
@Injectable({scope: Scope.TRANSIENT})
export class CatService {
constructor(
private petService: CatPetService
) {}
}
@Injectable({scope: Scope.TRANSIENT})
export class CatPetService {
constructor() {}
}
ModuleRef.create()
is called@Injectable({scope: Scope.TRANSIENT})
export class CatService {
constructor(
private petService: CatPetService,
private moduleRef: ModuleRef,
) {
this.init();
}
private async init() {
this.petService = await this.moduleRef.create(CatPetService);
}
}
Fixed in the latest release. Thanks for reporting!
I updated to 7.0.10 but still the issue persists exactly as it was before. Could you please check? https://github.com/MickL/nest-di-bug
[Nest] 3547 - 05/12/2020, 12:38:10 PM [NestFactory] Starting Nest application...
[Nest] 3547 - 05/12/2020, 12:38:10 PM Created CatPetService
[Nest] 3547 - 05/12/2020, 12:38:10 PM [InstanceLoader] AppModule dependencies initialized +1ms
[Nest] 3547 - 05/12/2020, 12:38:10 PMaddCat()
called, should create aCatService
and aCatPetService
now...
[Nest] 3547 - 05/12/2020, 12:38:10 PM Created CatService
[Nest] 3547 - 05/12/2020, 12:38:10 PM Meow!
(node:3547) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'log' of undefined
Oh, I forgot to mention. Please, use the resolve()
instead of create()
. create()
is used to instantiate providers that aren't a part of the module. Ill add an appropriate warning message
Thank you it is working now!
But still there seems to be an "error"? It creates an unnecessary instance on startup:
Updated my repo.
Thanks for reporting! Please, update to the 7.0.11 and let me know if this issue still persists
Works perfectly now for .resolve()
. For .create()
it has the same error of not created dependencies, but this is the correct behavior? No warning message, yet.
Maybe the documentation is misleading in this case. At Instantiating classes dynamically it shows create()
. I would expected this headline at Resolving scoped providers.
Most helpful comment
Fixed in the latest release. Thanks for reporting!