Build Status npm version Dependency Status

Injecting

A simple javascript dependency inject processor, work great with Promise.

Example

simple injection:

var injecting = require('injecting');
var app = injecting();
app.register('name', 'jack');
app.register('person', function(name) {
    this.name = name;
});

app.invoke(function(person) {
    console.log(person.name); // jack
});

recursive injection:

var injecting = require('injecting');
var app = injecting();
app.register('place', 'pacific');
app.register('cat', function() {
    this.name = "white cat";
});
app.register('person', function(cat) {
    this.name = "robot";
    this.pet = cat;
});
app.register('story', function(place, person){
    return {
        place: place,
        person: person.name,
        pet: person.pet.name
    };
});
app.invoke(function(story){
    console.log(story);
    /* should be
    {
        place: 'pacific',
        person: 'robot',
        pet: 'white cat'
    };
    */
});

Async Function


var injecting = require('injecting');
var app = injecting();
app.register('name', function() {
  return new Promise(function(resolve) {
    setTimeout(function () {
      resolve('jack');
    }, 1000);
  });
});

// will wait for name resolved
app.register('person', function (name) {
  return new Promise(function(resolve) {
    setTimeout(function () {
      resolve({name: name, age: 10});
    }, 1000);
  });
});


app
  .get('person')
  .then(function(person) {
    console.log(person); // should be {name: 'jack', age: 10}
  });

Please refer to the test cases for more examples.

methods

constant(name, value)

register a constant as dependency.

service(name, constructor)

register a service as dependency. notice you have to pass a function for it. injecting will call the constructor and return the instance the first time you inject. It will return the same instance for later use.

register(name, obj|fn)

register the argument as dependency. automatically register as constant if the second argument is object|string|number, and register as service if the second argument is function.

invoke(fn)

invoke a function and automatically inject for its arguments. Expect to return a promise.

get(name)

get a particular injection in promise form.

License

MIT