Accessing the NestJS DI container directly allows for seamless integration of dependency

I have been using NestJS for the past 4 months after working with PHP for 5 years, mainly with Symfony. With PHP, I had the ability to access the compiled DI container and retrieve any necessary service from it.

For example, in an application with services (A, B, C) where A depends on B and C, I could easily call the container in controllers or other services that were aware of it, and utilize the compiled A or C services as needed.

Is there a similar option in NestJS DI to call a specific service by some ID? I've tried looking for it, but all my searches lead to using compiled services only without direct access.

UPD: I am curious about accessing the DI container from a non-@Injectible class. For instance:

export class StatefulCruncherClass{

    constructor(private dataToCrunch:any){
          
    }

    async crunch(){
        if (this.dataToCrunch.isObject){
             return NestJs.getDI().get('ObjectsCruncher').crunch(this)
        } else {
             return NestJs.getDI().get('ArrayCruncher').crunch(this)
        }
    }
}

Answer №1

Utilizing moduleRef is the recommended approach for this scenario (documentation)

@Injectable()
export class CatsService implements OnModuleInit {
  private service: Service;
  constructor(private moduleRef: ModuleRef) {}

  onModuleInit() {
    this.service = this.moduleRef.get(Service);
  }
}

Attempting to access the container in a static context without injection raises concerns about design and architecture, potentially causing conflicts with the framework's functionality.

What is driving the need for non-injectable access?

Your other choice would involve exposing the Nest application instance for external importation, although I strongly discourage this practice.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using an aria-label attribute on an <option> tag within a dropdown menu may result in a DAP violation

Currently, I am conducting accessibility testing for an Angular project at my workplace. Our team relies on the JAWS screen reader and a helpful plugin that detects UI issues and highlights them as violations. Unfortunately, I've come across an issue ...

Sanity.io's selection of schema field types for efficient and convenient

Hey there, guys! I recently started using Sanity.io and I'm curious whether there's a way to enhance my code efficiency and reuse certain fields across different schemas. I had an idea that goes something like this: cars.ts: export default { ...

Looking for guidance on where to find a functional code sample or comprehensive tutorial on working with ViewMetadata in Angular2

I am currently trying to understand the relationship between viewmetadata and the fundamental use of encapsulation: ViewEncapsulation, including ViewEncapsulation.Emulated and ViewEncapsulation.None. Here is a link for further information: https://angula ...

Testing a NestJS service with multiple constructor parameters can be done by utilizing various techniques such as dependency

Content When testing a service that needs one parameter in the constructor, it's essential to initialize the service as a provider using an object instead of directly passing the service through: auth.service.ts (example) @Injectable() export class ...

Adjust the color of the entire modal

I'm working with a react native modal and encountering an issue where the backgroundColor I apply is only showing at the top of the modal. How can I ensure that the color fills the entire modal view? Any suggestions on how to fix this problem and mak ...

Step-by-step guide on releasing declaration files (.d.ts) for vscode plugins

I developed a vscode extension that provides an API for other extensions to utilize (by returning a value in the activate() function). I am interested in releasing a scoped npm package containing a declaration file (.d.ts) to help extension developers eas ...

Setting up data in Firebase can be challenging due to its complex structure definition

https://i.stack.imgur.com/iclx7.png UPDATE: In my firebase structure, I have made edits to the users collection by adding a special list called ListaFavorite. This list will contain all the favorite items that users add during their session. The issue I a ...

What is the way to assign a variable to ngClass in Angular?

I'm currently working on creating modals that will display different content based on which button is clicked. Each button should trigger a unique modal to appear, each with its own specific content inside. When a button is clicked, the 'active&a ...

The interface does not allow properties to be assigned as string indexes

Below are the interfaces I am currently working with: export interface Meta { counter: number; limit: number; offset: number; total: number; } export interface Api<T> { [key: string]: T[]; meta: Meta; // encountered an error here } I h ...

I'm looking to mimic the DataSource from TypeORM in NestJS Jest tests - any suggestions on how to do

Attempting to create tests for a small NestJS project, focusing on the following code snippets: dummy.controller.ts @Controller(UrlConstants.BASE_URL + 'dummy') export class DummyContoller { constructor( private readonly sessionServi ...

The React Typescript error message: "Type '' is not compatible with type 'null'"

I have started working on a simple todo app using React and TypeScript. As I am creating a context, I encountered an error regarding the value of the content provider. <TodoContext.Provider value={contextValue}>{children}</TodoContext.Provider> ...

How to Utilize Class Members in a Callback Function in Angular 12 with Capacitor Version 3

When I click the "Device Hardware Back Button" using Capacitor 3.0, I'm trying to navigate to the parent component with the code below. The device back button is working correctly, but I'm facing an issue where I can't access class members i ...

Finding the percentage scores for five different subjects among a class

As a beginner in TypeScript, I am still learning the ropes. Here is the code snippet I used to calculate percentage: pere() { this.E=(((+this.English+ +this.Tamil+ +this.Maths+ +this.Science+ +this.Social)/500)*100); console.log(this.E); The result w ...

Assign Attribute to a Different Data Transfer Object

I have a query regarding my nestjs project - is it possible to assign a value Attribute to another Dto? Specifically, I'm looking to assign idData to the id in IsUniqueValidator. I attempted the following code but it resulted in 'undefined&apos ...

When transitioning to generics, the narrowing of types in TypeScript is sometimes lost

I am intrigued by this scenario where Test1 fails while Test2 succeeds. I wonder if there is a way to have Test1 pass without altering the generic signature: enum TableType { Shipment = "Shipment", Batch = "Batch", } type Test& ...

Challenges encountered when sending an HTTP post request in Ionic 2 with Angular 2

Whenever I try to make a post request in my ionic2 application, I encounter an error without any specific message. It seems like there is something wrong with my Angular2 post request. Below is the function I am using for the request: load(username, pass ...

The recursive component is functional exclusively outside of its own scope

I'm facing an issue where my recursive component is not nesting itself properly. The problem arises when I try to use the Recursive component inside another Recursive component. Although the root is correctly inserted into the Recursive component fro ...

Tips for creating a typescript typeguard function for function types

export const isFunction = (obj: unknown): obj is Function => obj instanceof Function; export const isString = (obj: unknown): obj is string => Object.prototype.toString.call(obj) === "[object String]"; I need to create an isFunction method ...

The NestJs project fails to display the updates when using the "tsc" command before running either "npm run start" or "npm run start:dev"

As a beginner in nestjs, I decided to start a tutorial to learn more about it. However, whenever I make updates or changes to my code, I don't see any changes reflected in the results. Can someone please assist me with this issue? Below are my tsconfi ...

Guide to building a nested React component

My custom dropdown component requires 2 props: trigger (to activate the dropdown) list (content to display in the dropdown) Below is the implementation of my component: import { useLayer } from "react-laag"; import { ReactElement, useState } fr ...