Skip to content
Mauro Gadaleta edited this page Mar 14, 2017 · 5 revisions

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

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