#How to use moduleRef.get with option `each: true` in order to reiceive multiple service instances

4 messages · Page 1 of 1 (latest)

buoyant violet
#

Hello,
in the moduleRef.get method there is now the possibility to set the option each: true in order to receive multiple service instances. In my case i try to receive multiple implementations of a service from the same module. How to use this feature in the right way? Here is the full sandboxcode: https://codesandbox.io/p/devbox/nestjs-forked-rhd99z?file=%2Fsrc%2Fapp.service.ts%3A9%2C56&workspaceId=9f28bd65-2a5b-4909-a9b3-1d7a9a1bc944


@Injectable()
export class AppService {
  private readonly animals: Animal[];
  constructor(private readonly moduleRef: ModuleRef) {
    // use moduleRef to receive 
    this.animals = this.moduleRef.get<Animal>('animals', {
      strict: true, // in order to make sure finding all animal services from same module
      each: true, // from different modules this is 
    });
    console.log(this.animals.length); // here i would like to expect dog and cat
    this.animals.forEach(a => a.speak());
  }
}

app.module.ts

    {
      provide: 'animals',
      useClass: CatService,
    },
    {
      provide: 'animals',
      useClass: DogService,
    }

I just receive one instance all the time and i think it is related to the fact, that i use the same token for different implementations. When i set strict: false i am able to receive multiple instances with the same token, if they are coming from different modules ( (not implementet in my provided sandbox). But i would like to receive the DogService and CatService from the same module. The idea is, when adding multiple implementations in the whole application (also in the same module), they could just be registered with the same token. The moduleRef would do the rest and find all implementations - no list of providers to maintain. How to use the each: true option correctly?

Thanks a lot an best regards
Andreas

lunar sphinx
#

I think the link is wrong

buoyant violet
merry quest
#

Hey @buoyant violet I could be wrong, but I think that is not possible to register multiple providers with the same token into a single module, the option each: true would return multiple instances only if there were other modules containing the animal provider.

You could try using the explorer pattern to find the providers you need.
https://github.com/nestjs/nest/pull/12107

GitHub

PR Checklist
Please check if your PR fulfills the following requirements:

The commit message follows our guidelines: https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md
Tests for the chan...