Danyal Sandeelo
Danyal Sandeelo

Reputation: 12401

How to get an object from NestJS container

How can I get an injected object from the container in nestjs?

This is something in Spring (Java). We can get the objects from the container like this:

CustomerClass myClass = applicationContext.getBean("CustomerClass");

Do we have anything in NestJS like that?

Upvotes: 1

Views: 1434

Answers (1)

Tobias S.
Tobias S.

Reputation: 23885

Yes, that exists.

This is how you would retrieve a service called TaskService from the app.

const app = await NestFactory.createApplicationContext(AppModule);
const tasksService = app.get(TasksService);

Of course you should always consider if you really need an instance of a service outside of the NestJs module system. If possible stay inside the application and inject the services.

Upvotes: 1

Related Questions