IoC for Javascript & Node.js

Dependency injection (DI)

With the IoC design pattern (Inversion of Control), object management is entrusted to a dedicated IoC container.

In a IoC container is simply a Collection of keys / values. Each value is associated with his key corresponding.

Like this:

var container = {
  key1: 'value 1',
  key2: 'value 2',
  // ...

In a Noder instance, the main IoC container is an instance of Collection class accessible via the property noder.$di.

Like this:

noder.$di.set('keyName', 'value of keyName');

The IoC container is responsible for creating items required and delivered via injection. This injection can actually be done in several ways.

Methods that support dependency injection


Simple injection:

noder.$di.set('hello', function(name) {
  return 'Hello ' + name;

// result = 'Hello World'
var result = noder.$inject('hello', function(hello) {
  return hello('World');

Several dependencies (bellow, hello() is called before injection):

// Setter-Injection
noder.$di.set('name', 'Sarah Connor');

// result = 'Hello Sarah Connor'
var result = noder.$invoke(['hello', 'name'], function(hello, name) {
  return hello(name);

Injection in a service provider:

// Constructor-Injection
noder.$provider('providerId', 'hello', function(hello) {
  return hello('World');

// result = 'Hello World'
var result = noder.$di.get('providerId');

Using directly the dependencies in the scope (this) of a given function:

noder.$apply(function() {

  // true
  console.log(this.$di === noder.$di);

  // Sarah Connor

  // Hello Sarah Connor

  // Hello World

See in the API doc:


For bundled the code to re-use easily across multiple projects or for redistribute, it may be useful to create a plugin.