-
Notifications
You must be signed in to change notification settings - Fork 37
Home
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.
- Installation
- Configuration Files
- Parameters
- Defining Services Dependencies Automatically (Autowiring)
- Binding Arguments by Name
- Keyed Services
- Conditional Services
- Compiling the Container
- Container Validation
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 MailerYou 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 MailerThen 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');Copyright © 2023-2024 Mauro Gadaleta