Nest: How to Implement service locator with Nest.js?

Created on 8 Feb 2018  路  3Comments  路  Source: nestjs/nest

I'm submitting a question.

In one of my factories I need to dynamically pull out services out from nestjs container. Normally in IoC containers you have the ability to inject the container itlsef.

So I want to inject something like Execution Context into my service and then use it's method get() to resolve whatever I want.

Here's example of what it could look like:

@Component()
export class Factory {
    constructor(
         private context: INestExecutionContext
    ) {}

    create(type) {
        return this.context.get(type);
    }
}

Is there is a way to achieve that ?

Thanks.

Most helpful comment

Hi, I guess you can do it like this:

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

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

Though, as far as I'm concerned the limitation is that you can do it like this only to get components provided inside the same module.

See here: https://github.com/nestjs/nest/issues/258#issuecomment-355237100

All 3 comments

Hi, I guess you can do it like this:

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

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

Though, as far as I'm concerned the limitation is that you can do it like this only to get components provided inside the same module.

See here: https://github.com/nestjs/nest/issues/258#issuecomment-355237100

@sqrter That's quite enough, thank you!

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings