dep-injector

0.2.1 • Public • Published

node-dep-injector

Build Status

Dep-injector is a dependecy injector for Node.js. It supports lazy loading by registering factory methods, not just instantiated dependencies. In this case the factory method will be called only when you inject it first time.

Usage

var DI = require('dep-injector');
var di = new DI();
 
di.register('foo', 1);
di.registerFactory('bar', function(foo) {
  console.log('bar');
  return foo + 1;
});
 
di.get('foo'); // 1
di.get('bar'); // 2 , and logs: bar
 
var fn = di.inject(function(bar) {
  return bar;
});
 
fn(); // 2 , without console.log
 

Methods

register(name, dep)

Registers a named dependency.

registerFactory(name, factoryMethod, [additionalDeps])

Registers a factory method. You can add addtional dependencies, and they will be injected when calling the factory method.

get(name)

Returns the named dependency, and instantiate it if it's a factory and the instance doesn't exist.

inject(fn, [additionalDeps])

Injects the required dependencies into the function, and returns another function. By calling the returned function you can resolve the dependencies and run the originally given function.

Running Tests

npm test

Licence

MIT © Gabor Pihaj

Package Sidebar

Install

npm i dep-injector

Weekly Downloads

0

Version

0.2.1

License

MIT

Last publish

Collaborators

  • voidcontext