desire

Dependency Injection Container in less than 50 lines

desire

Dependency Injection Container in less than 50 lines of code.


To define a component that desires other components, create a component factory.

var App = function(desire) {
 
  var ui = desire('ui')
 
  return {
    runfunction() {
      console.log('application starts')
      ui.show()
      console.log('ui is visible')
    }
  }
 
}

Other components do the same:

var UI = function(desire) {
 
  return {
    showfunction() {
      console.log('display ui')
    }
  }
 
}

To run, create a container, register components, and desire.

var Desire = require('./.')
var desire = new Desire()
 
desire.register({
  app: App,
  ui: UI
})
 
var app = desire('app')
 
app.run()

You can manually inject dependencies too.

Because a component factory is just a function that desires other components, we can create a Desire() and pass it to the factory ourselves.

var fakeUi = { showfunction() { console.log('fake ui') } }
 
var app2 = App(new Desire({ ui: Desire.value(fakeUi) }))
 
app2.run()