#Accessing env vars when registering providers

6 messages · Page 1 of 1 (latest)

dull sand
#

Hello - when conditionally registering different implementations of interfaces (or abstract classes) as providers, is there any way of using the config service? Or is accessing process.env directly the only option?

unkempt lake
#

for those providers that you're registering dynamically, you can also inject any other provider that is available to the module as usual. So yes, you can use ConfigService

#

can you show us an example on how you're doing the provider registration?

fresh zephyr
#

Two options:

  1. if you want to conditionally include/exclude providers from the providers array, your only options is reading process.env directly (or using ConditionalModule, which is basically the same thing with extra steps). The ConfigService is only available via DI.
#
  1. If you only want to switch implementations, you can use a factory provider with moduleRef
providers: [
  {
     provide: MyProvider,
     inject: [ConfigService, ModuleRef],
     useFactory: (config, moduleRef) => {
        const kind = config.get('kind')
        if (kind == 'typeA') {
          return moduleRef.create(TypeAProvider)
        } else {
          return moduleRef.create(TypeBProvider)
        }
     }
  }
]
dull sand
#

@fresh zephyr Amazing thank you - the second scenario is exactly what I was aiming for. Much appreciated !