I want to create an instance of a dynamically loaded class trough Nest.js dependency injection service.
In Angular I would use Injector.create
, what would be the equivalent in Nest.js ?
The @Injectable() decorator marks the CatsService class as a provider. cats.service.ts. import { Injectable } from '@nestjs/common'; import { Cat } from './interfaces/cat.interface'; @Injectable() export class CatsService { private readonly cats: Cat[] = []; findAll(): Cat[] { return this.
Nest. JS helps build lightweight, well-structured and amazing microservices and helps evolve the technology stack. The microservice architecture enables the rapid, frequent and reliable delivery of large, complex applications. Out-of-the-box tools and features make development, extension, and maintenance efficient.
Nest provides the ModuleRef class to navigate the internal list of providers and obtain a reference to any provider using its injection token as a lookup key. The ModuleRef class also provides a way to dynamically instantiate both static and scoped providers.
NestJS Modules are Singletons by default. Their Providers are also singletons when they are provided from within the same module. However, there are cases where we want to use just a single solo class as a provider to a couple or more modules. In such cases, we can use the solo class as singleton or not.
First of all you should get a ModuleRef which references current module, and then use its "get" method to get an instance.
@Injectable()
export class AppletService {
files: FileService;
constructor(
private moduleRef: ModuleRef,
) {
this.files = moduleRef.get(FileService);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With