Documentation

Conditional Services

Conditional Services

Register services only when environment or runtime conditions are satisfied.

Services can be conditionally registered based on environment variables, the presence of other services, or any custom runtime logic. Conditions are evaluated at compile() time in two phases.

JavaScript / TypeScript API

Import Condition alongside ContainerBuilder:

import { ContainerBuilder, Condition } from 'node-dependency-injection'

Available conditions

FactoryPhaseRegisters when…
Condition.envExists('VAR')1Environment variable VAR is set
Condition.envEquals('VAR', 'value')1process.env.VAR === 'value'
Condition.custom(() => expr)1The callback returns truthy
Condition.all(cond1, cond2, …)1All sub-conditions pass
Condition.any(cond1, cond2, …)1At least one sub-condition passes
Condition.missing('service.id')2No service with that id is registered
Condition.serviceExists('service.id')2A service with that id is registered

Phase 1 conditions are evaluated first; services that fail are removed before phase 2 conditions are checked.

definition.setCondition(condition)

Attach any Condition instance to a definition:

container.register('cache.redis', RedisCache)
  .setCondition(Condition.envExists('REDIS_URL'))

definition.whenMissing(id) — TryAdd pattern

Registers the service only when no service with id is already registered (after phase 1):

container.register('cache.memory', InMemoryCache)
  .whenMissing('cache.redis')

definition.whenServiceExists(id)

Registers the service only when a service with id is registered:

container.register('metrics', Prometheus)
  .whenServiceExists('http.server')

Combining conditions

container.register('feature.x', FeatureX)
  .setCondition(Condition.all(
    Condition.envEquals('NODE_ENV', 'production'),
    Condition.envExists('FEATURE_X_ENABLED')
  ))

YAML / JSON / JS config files

Use the when: key inside any service definition:

services:
  cache.redis:
    class: 'services/cache/RedisCache'
    when:
      env_exists: REDIS_URL

  cache.memory:
    class: 'services/cache/InMemoryCache'
    when:
      missing: cache.redis

  metrics.prometheus:
    class: 'services/metrics/Prometheus'
    when:
      service_exists: http.server

  logger.verbose:
    class: 'services/logger/VerboseLogger'
    when:
      env_equals:
        var: LOG_LEVEL
        value: debug

Supported when keys: env_exists, env_equals, missing, service_exists.

all / any / custom are only available via the programmatic API.


Two-phase evaluation

Phase 1 — evaluated independently, in any order:
env_exists, env_equals, custom, all, any

Phase 2 — evaluated after phase-1 removals:
missing, service_exists

This guarantees that missing and service_exists conditions see the final set of services after all environment-based conditions have been applied.