Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nest.js get injector instance

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 ?

like image 601
Rafael Munitić Avatar asked Feb 28 '18 13:02

Rafael Munitić


People also ask

What is @inject in NestJS?

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.

Is NestJS worth learning?

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.

What is ModuleRef in NestJS?

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.

Are NestJS services singletons?

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.


1 Answers

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);
  }
}
like image 117
Alexey Petushkov Avatar answered Sep 21 '22 13:09

Alexey Petushkov