Documentation

Binding Arguments by Name

Binding Arguments by Name

Only available for TypeScript with Autowiring

Bind scalar constructor arguments by parameter name when type-based autowiring is not enough.

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.

Example: Injecting a Scalar Parameter

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.

Programmatic API

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'

YAML Configuration

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: 3

Using Environment Variables

Bind 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);

Precedence

Binds are global defaults. If a service definition explicitly declares its own arguments, those take precedence over any bind values.

Notes

  • 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.