boxed-injector
![Coverage Status](https://coveralls.io/repos/github/giddyinc/boxed-injector/badge.svg?branch=master)
Dependency Injection Tools
Installation
$ npm install --save boxed-injector
Overview
This is a set of lightweight Dependency Injection components that can be used in both client and server javascript code.
There are 4 components.
- Injector (Dependency Injection Container)
- Locator (Service Locator, which leverages the DI Container)
- Inject (Higher Order Component for resolving dependencies declaratively into React containers) - See separate README
- Injectable (Wrapper around React Components for directly injecting resolved props) - See separate README
Installation
$ npm install --save boxed-injector
Usage
'use strict';
const parts = [];
class EngineFactory {
static get inject() {
return [
'Parts'
];
}
constructor(parts) {
this.parts = parts;
}
}
class CarFactory {
static get inject() {
return [
'EngineFactory'
];
}
constructor(engineFactory) {
this.engineFactory = engineFactory;
}
}
const Injector = require('boxed-injector').Injector;
let injector = new Injector();
injector.register('Parts', parts);
injector
.factory('EngineFactory', EngineFactory)
.factory('CarFactory', CarFactory);
const carFactory = injector.get('CarFactory');
console.log(carFactory);
const Locator = require('boxed-injector').Locator;
Locator.set(injector);
injector = Locator.get();
const sameCarFactory = injector.get('CarFactory');
console.log(sameCarFactory);
console.log(carFactory === sameCarFactory);
Create
Resolves a factory's dependencies and then instantiates an instance with the given args. Will call the constructor (new) on a registered instance that is a function.
function Engine() {}
function Car(engine, color) { this.engine = engine; this.color = color; }
Car.inject = ['Engine'];
injector.factory('Engine', Engine);
injector.factory('Car', Car);
const car = injector.create('Car', ['blue']);
Middleware
Middleware functions are executed every time a service is accessed from the container (or on a factory, the first time it's accessed).
Global middleware as well as service/factory specific middleware is supported and is executed in the order of registry (FIFO).
Note that registered instances are singletons and mutations will affect all consumers.
Middleware is synchronous, and is passed an object as follows:
{
name: 'ExampleService',
depends: ['ThingItsDependentOn', 'OtherThing'],
instance: { thing: {}, other: {} },
factory: ExampleService
}
Usage:
injector.middleware(entity => console.log('before global'));
injector.middleware('baz', entity => console.log(entity.name));
injector.middleware(entity => console.log(`before global again - resolving ${entity.name}`));
injector.register('baz', result);
injector.middleware(() => console.log('after global'));
injector.middleware('baz', entity => console.log(entity.name));
injector.get('baz');
Contributing
We look forward to seeing your contributions!
License
MIT © Ben Lugavere