A very light and simple (easy) Dependency Injection.
Izidi is a simple Helper to manage components and dependency injection.
You have first to require the izidi module
var izidi = require("izidi");
You have next some convenient methods to register components to the container :
var obj = new MyObject();
izidi.container.register("obj1", obj);
And method to access to the components by name :
var c = izidi.container.get("obj1");
You can next create component in their own JS file. In each component file, you have to :
- require the izidi component
- create a factory by invoking the buildFactory of the izidi FactoryBuilder object
- surchage the createAndRegister method and return the usable component
- export your factory
Here is a code sample :
var factory = izidi.factoryBuilder.buildFactory();
factory.createAndRegister = function( depMap ){
izidi.container.factoryArgsChecks( "ComponentTwo", depMap, ['logger', 'info', 'message'] );
var component = new Component( depMap.logger, depMap.info, depMap.message );
return component;
};
module.exports = factory;
You can notice that the container propose a factoryArgsChecks to verify injected parameters.
You can define an array with component descriptions. Each description is a JS object with :
- a
name
property : name od the component in the container - a
module
property : relative path to the corresponding JS module file - a
dependencies
property : array oth component names that have to be injected in your component
Example :
var componentDefs = [
{
name: "c1",
module: "./samples/factories/componentOne.js",
dependencies: [
"logger",
"info"
]
},
{
name: "c2",
module: "./samples/factories/componentTwo.js",
dependencies: [
"logger",
"info",
"message"
]
}
];
And then load all defined components :
izidi.container.loadComponents( componentDefs );
So, you can use them in you main code :
var c1 = izidi.container.get("c1");
c1.hello();
var c2 = izidi.container.get("c2");
c2.hello();
See file id the
samples/
directory and subdirectories for complete sample.