Skip to content

Instantly share code, notes, and snippets.

@xtenduke
Created May 2, 2022 05:41
Show Gist options
  • Save xtenduke/5ff7ddb6206f40f9317788dcea22b1d2 to your computer and use it in GitHub Desktop.
Save xtenduke/5ff7ddb6206f40f9317788dcea22b1d2 to your computer and use it in GitHub Desktop.
NestJS get injected instance by name
// Pull out instance of a class from moduleContainer
// 'nicer' alternative to globals
// loops over all instances in a module, so probably don't do this at runtime
import {Injectable, Inject} from "@nestjs/common";
import {ConfigType} from "@nestjs/config";
import {ModulesContainer} from "@nestjs/core";
import {InstanceWrapper} from "@nestjs/core/injector/instance-wrapper";
const config.name = 'MyInjectedClass';
const instances = Array.from(this.modulesContainer.values())
.map((module) => {
return Array.from(module['providers'].values())
}).reduce((arr1, arr2) => {
return arr1.concat(arr2);
}).filter((instance: InstanceWrapper) => {
return instance.name === config.name;
});
if (instances.length > 1) {
throw new Error(`More than one injected instance of ${config.name} - in this module`);
}
if (instances.length === 0) {
throw new Error(`No injected instances of ${config.name} - please inject it somewhere`);
}
const instance = instances[0].instance as InstanceType < any > ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment