Direct access to NestJS DI container

Viewed 566

I'm working with NestJS for 4 month, and previously was working with PHP for 5 years. With PHP and Symfony in particular I had an option to access compiled DI container and get any service from it for my need.

Like if we have an application with services (A B C) and A is dependent of B and C I was able to call for container in controllers and even in other services, which are aware of container, and use compiled A or C services for my needs.

Is there any option like this with NestJS DI - call certain service by some ID? I tried to search for it but everything ends up in using compiled services only with no direct access.

UPD: I'm interested in accessing DI container from a non-@Injectible class. For example:

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)
        }
    }
}
1 Answers

You can use moduleRef for this (docs)

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

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

Trying to access the container in a static (non injected) context seems suspicious to me and I think it likely points to a design/architecture issue for the feature you're trying to build. You're definitely "fighting" the framework at that point.

What is the reason that you need to have access in a non injectable way?

Your only other option would be somehow make the actual Nest application instance available to be imported into other files but I would strongly advise against it.

Related