#Inject only partial dependencies

3 messages · Page 1 of 1 (latest)

lyric phoenix
#

I'm trying to instantiate multiple providers based on an env variable (comma separated list of names).
Except the first constructor argument (the value coming from the env variable array), all the others are the same. Is it possible to use a factory to provide the first argument and let nestjs to do the others so they're only declared in the service class (and not in the factory)?

something like this

const helloProviders = NAMES_LIST.map(name => ({
  provide: `HelloService_${name}`,
  useFactory: () => new HelloService(name, ...rest goes here)
}))

@Injectable()
export class HelloService {
  constructor(
    private readonly name: string,
    private readonly configService: ConfigService,
    ... other services ...
  ) {
#

or maybe have a way to just provide a value within that service instance, so that it's not constructed within the useFactory

amber ice
#

You could make a mixin, a function that returns a class reference, like the AuthGuard or FileInterceptor