NodeJS based service locator with explicit dependency management. Useful to keep track of your dependencies throughout the project and enable good testability.
$ npm install service-locator-demand
var locator = require('service-locator-demand');
locator.set('db', dbConnection);
locator.set('app', app);
// ERROR: this key is already defined
locator.set('db', anotherDbInstance);
// retrieve the instances again
locator.db.loadSomething();
locator.app.toggleImportantStuff();
// unset instances and set them again
locator.remove('db');
locator.set('db', anotherDbInstance);
// remove all instances
locator.clear();
console.log(locator.db); // undefined
// ####> in your main module
var locator = require('service-locator-demand');
locator.set('db', dbConnection);
locator.set('app', myApp);
locator.set('mail', myMailInstance);
// ####> in a satellite module
var loc = require('service-locator-demand');
// #### Demand the services you want to have
loc = loc.demand(module, 'db', 'app');
console.log(typeof loc.db); // --> 'object'
console.log(typeof loc.app); // --> 'object'
// services which where NOT demanded, CANNOT be accessed
console.log(typeof loc.mail); // --> undefined
'loc' is a readonly copy (facade) for the real locator. If something changes in the locator those changes will be adopted by the copy.
// ####> in a satellite module
var loc = require('service-locator-demand');
// will throw exception because of 'nonExistentModule'
loc = loc.demand(module, 'db', 'app', 'nonExistentModule');
$ npm install -g grunt-cli
$ npm install
$ npm test
Copyright (c) 2013 mantro.net GmbH <http://www.mantro.net/>