Skip to content
Mauro Gadaleta edited this page Jun 23, 2026 · 8 revisions

Node Dependency Injection

Standardize and centralize object creation with a lightweight, configurable container.

The Node Dependency Injection component allows you to standardize and centralize the way objects are constructed in your application.

v4.0.0 — Autowire now generates human-readable service IDs by default. See the Autowire and migration guide for details.

Recommended learning path (priority order)

  1. Installation
  2. Configuration Files
  3. Parameters
  4. Defining Services Dependencies Automatically (Autowiring)
  5. Binding Arguments by Name
  6. Keyed Services
  7. Conditional Services
  8. Compiling the Container
  9. Container Validation

Basic usage

You might have a simple class like the following Mailer that you want to make available as a service:

class Mailer {
    constructor () {
        this._transport = 'sendmail'
    }
}

export default Mailer

You can register this in the container as a service:

import {ContainerBuilder} from 'node-dependency-injection'
import Mailer from './Mailer'

let container = new ContainerBuilder()
container.register('mailer', Mailer)

An improvement to the class to make it more flexible would be to allow the container to set the transport used. If you change the class so this is passed into the constructor:

class Mailer {
    constructor (transport) {
        this._transport = tansport
    }
}

export default Mailer

Then you can set the choice of transport in the container:

import {ContainerBuilder} from 'node-dependency-injection'
import Mailer from './Mailer'

let container = new ContainerBuilder()
container
  .register('mailer', Mailer)
  .addArgument('sendmail')

You could then get your mailer service from the container like this:

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

let container = new ContainerBuilder()

// ...

let mailer = container.get('mailer');

Related guides

Clone this wiki locally