-
Notifications
You must be signed in to change notification settings - Fork 37
ConditionalServices
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.
Import Condition alongside ContainerBuilder:
import { ContainerBuilder, Condition } from 'node-dependency-injection'| Factory | Phase | Registers when… |
|---|---|---|
Condition.envExists('VAR') |
1 | Environment variable VAR is set |
Condition.envEquals('VAR', 'value') |
1 | process.env.VAR === 'value' |
Condition.custom(() => expr) |
1 | The callback returns truthy |
Condition.all(cond1, cond2, …) |
1 | All sub-conditions pass |
Condition.any(cond1, cond2, …) |
1 | At least one sub-condition passes |
Condition.missing('service.id') |
2 | No service with that id is registered |
Condition.serviceExists('service.id') |
2 | A service with that id is registered |
Phase 1 conditions are evaluated first; services that fail are removed before phase 2 conditions are checked.
Attach any Condition instance to a definition:
container.register('cache.redis', RedisCache)
.setCondition(Condition.envExists('REDIS_URL'))Registers the service only when no service with id is already registered (after phase 1):
container.register('cache.memory', InMemoryCache)
.whenMissing('cache.redis')Registers the service only when a service with id is registered:
container.register('metrics', Prometheus)
.whenServiceExists('http.server')container.register('feature.x', FeatureX)
.setCondition(Condition.all(
Condition.envEquals('NODE_ENV', 'production'),
Condition.envExists('FEATURE_X_ENABLED')
))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: debugSupported when keys: env_exists, env_equals, missing, service_exists.
all/any/customare only available via the programmatic API.
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.
Copyright © 2023-2024 Mauro Gadaleta