didi
A tiny inversion of control container for JavaScript.
About
Using didi
you follow the dependency injection / inversion of control pattern, decoupling component declaration from instantiation. Once declared, didi
instantiates components as needed, transitively resolves their dependencies, and caches instances for re-use.
Example
import { Injector } from 'didi';
function Car(engine) {
this.start = function() {
engine.start();
};
}
function createPetrolEngine(power) {
return {
start: function() {
console.log('Starting engine with ' + power + 'hp');
}
};
}
const carModule = {
'car': ['type', Car],
'engine': ['factory', createPetrolEngine],
'power': ['value', 1184]
};
const injector = new Injector([
carModule
]);
injector.get('car').start();
injector.invoke(function(car) {
console.log('started', car);
});
const car: Car = injector.get<Car>('car');
car.start();
For real-world examples, check out Karma or diagram-js, two libraries that heavily use dependency injection at their core. You can also check out the tests to learn about all supported use cases.
Usage
Learn how to declare, inject and initialize your components.
Declaring Components
By declaring a component as part of a didi
module, you make it available to other components.
type(token, Constructor)
Constructor
will be called with new
operator to produce the instance:
const module = {
'engine': ['type', DieselEngine]
};
factory(token, factoryFn)
The injector produces the instance by calling factoryFn
without any context. It uses the factory's return value:
const module = {
'engine': ['factory', createDieselEngine]
};
value(token, value)
Register a static value:
const module = {
'power': ['value', 1184]
};
Injecting Components
The injector looks up dependencies based on explicit annotations, comments, or function argument names.
Argument Names
If no further details are provided the injector parses dependency names from function arguments:
function Car(engine, license) {
}
You can use comments to encode names:
function Car( e, x) {
}
$inject
Annotation
You can use a static $inject
annotation to declare dependencies in a minification safe manner:
function Car(e, license) {
}
Car.$inject = [ 'engine', 'license' ];
Array Notation
You can also the minification save array notation known from AngularJS:
const Car = [ 'engine', 'trunk', function(e, t) {
}];
Partial Injection
Sometimes it is helpful to inject only a specific property of some object:
function Engine( power) {
}
const engineModule = {
'config': ['value', {engine: {power: 1184}, other : {}}]
};
Initializing Components
Modules can use an __init__
hook to declare components that shall eagerly load or functions to be invoked, i.e., trigger side-effects during initialization:
import { Injector } from 'didi';
function HifiComponent(events) {
events.on('toggleHifi', this.toggle.bind(this));
this.toggle = function(mode) {
console.log(`Toggled Hifi ${mode ? 'ON' : 'OFF'}`);
};
}
const injector = new Injector([
{
__init__: [ 'hifiComponent' ],
hifiComponent: [ 'type', HifiComponent ]
},
...
]);
injector.init();
Overriding Components
You can override components by name. That can be beneficial for testing but also for customizing:
import { Injector } from 'didi';
import coreModule from './core';
import HttpBackend from './test/mocks';
const injector = new Injector([
coreModule,
{
httpBackend: [ 'type', HttpBackend ]
}
]);
Type-safety
didi
ships type declarations that allow you to use it in a type safe manner.
Explicit Typing
Pass a type attribute to Injector#get
to retrieve a service as a known type:
const hifiComponent = injector.get<HifiComponent>('hifiComponent');
hifiComponent.toggle();
Implicit Typing
Configure the Injector
through a service map and automatically cast services
to known types:
type ServiceMap = {
'hifiComponent': HifiComponent
};
const injector = new Injector<ServiceMap>(...);
const hifiComponent = injector.get('hifiComponent');
Credits
This library builds on top of the (now unmaintained) node-di library. didi
is a maintained fork that adds support for ES6, the minification safe array notation, and other features.
Differences to node-di
- supports array notation
- supports ES2015
- bundles type definitions
- module initialization + module dependencies
License
MIT