Last active
January 3, 2016 11:19
-
-
Save ellman/8455877 to your computer and use it in GitHub Desktop.
simple example of dependency injection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var dependable = require('dependable'), | |
container = dependable.container(); | |
// Could be your db connection | |
var mongoose = {} | |
// Random dependency | |
container.register('anotherDependency', 'I do nothing right now'); | |
// The dbAdmin "module" could be another that we want to make that might | |
// require some dependency/functionality from another module | |
// and even possibly extend it. | |
container.register('dbAdmin', function (database, anotherDependency) { | |
var dbAdmin = {}; | |
//here for example we overide the standard showCollections and do | |
//something else | |
dbAdmin.showCollections = function showCollections() { | |
return [ | |
"I'm the dbAdmin module and I show you some stuff", | |
'Collections ' + database.showCollections(), | |
'Other dependancey... '+anotherDependency | |
].join('\n'); | |
}; | |
return dbAdmin; | |
}); | |
// We can register the database and other modules can depend on it | |
// in reality we would be doing more interesting things but this is | |
// pretty obvious example | |
container.register('database', { | |
connection: mongoose, | |
showCollections : function() { | |
return { "users": {}, "articles" : {} }; | |
} | |
}); | |
// Finaly we resolve our "module" | |
container.resolve({}, function (dbAdmin) { | |
console.log(dbAdmin.showCollections()); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment