-
-
Notifications
You must be signed in to change notification settings - Fork 0
Usage (javascript)
You have the following application structure:
- index.js
- foo.js
- bar.js
index is the main entry point of your application. Foo is a component (a class) that we want to instantiate inside index. Foo has a dependency to bar and to a logger.
Bar is another component and has a dependency to a logger.
A component is a standard node.js function (typically a class constructor). Here for example bar.js file that export Bar class:
bar.js
function Bar(logger){
this._logger = logger;
}
Bar.prototype.helloBar = function(){
this._logger.log("hello from bar");
}
module.exports = Bar;
As you can see there isn't any special code or annotation. All you have to do is to export a function that will be called automatically with all the dependencies resolved, in the above case the logger instance.
Foo component is very similar except that it has a dependency to logger and bar:
foo.js
function Foo(bar, logger){
this._logger = logger;
this._bar = bar;
}
Foo.prototype.helloFoo = function(){
this._logger.log("hello from foo");
this._bar.helloBar();
}
module.exports = Foo;
When Foo will be created an instance of class Bar will be passed. And now take a look at our application entry point, index.js, where we wire up all the components together:
index.js
var ShelfDependency = require("shelf-dependency");
var container = new ShelfDependency.Container();
container.register("foo", require("./foo.js"));
container.register("bar", require("./bar.js"));
container.register("logger", console);
var foo = container.resolve("foo");
foo.helloFoo();
Basically we create the ShelfDependency.Container and register all the components (Bar, Foo and an object for the logger). Finally we resolve our root class Foo.