-
Notifications
You must be signed in to change notification settings - Fork 37
Bind
When using Autowire, the container automatically resolves dependencies by type — injecting services by their class or interface type annotation. However, scalar parameters (such as string, number, or boolean) cannot be resolved by type alone, since there's no class to look up.
Binding lets you map constructor parameter names to concrete values, so that scalar arguments are injected automatically alongside your service dependencies.
Consider a service that requires an email address alongside a service dependency:
export default class MailerService {
constructor(
private readonly adminEmail: string,
private readonly transport: MailTransport,
) {}
sendReport(): void {
// uses this.adminEmail and this.transport
}
}Without binding, adminEmail would be skipped during autowiring (since string is not a resolvable service). With binding, you map the parameter name adminEmail to a concrete value.
Use addBind(name, value) on the container before calling autowire.process():
import { ContainerBuilder, Autowire } from 'node-dependency-injection';
const container = new ContainerBuilder(false, '/path/to/src');
container.addBind('adminEmail', 'manager@example.com');
container.addBind('retryCount', 3);
const autowire = new Autowire(container);
await autowire.process();
await container.compile();
const mailer = container.get(MailerService);
// mailer.adminEmail === 'manager@example.com'Add a bind map under _defaults in your services file:
# config/services.yaml
services:
_defaults:
autowire: true
rootDir: ../src
bind:
adminEmail: 'manager@example.com'
retryCount: 3Bind values support the same syntax as regular service arguments, including environment variable resolution:
services:
_defaults:
autowire: true
rootDir: ../src
bind:
adminEmail: '%env(ADMIN_EMAIL)%'
databaseUrl: '%env(DATABASE_URL)%'Or programmatically using process.env:
container.addBind('adminEmail', process.env.ADMIN_EMAIL);Binds are global defaults. If a service definition explicitly declares its own arguments, those take precedence over any bind values.
- Binds are matched by parameter name — the name must exactly match the constructor parameter name.
- Binds only apply to parameters that cannot be resolved by type (primitives, unresolvable types). If a parameter has a resolvable class or interface type, the type-based injection takes priority.
- Binds are scoped to the container instance — multiple YAML files loaded into the same container will share and accumulate binds.
Copyright © 2023-2024 Mauro Gadaleta