A simple IOC container for Node
A simple Inversion of Control container for node.js.
Sanders builds object graphs that have dependencies, while hopefully staying out of your way as much as possible.
Maybe you don't. If you are happy using
require with file paths, feel free to keep doing that.
In working test-first on a socket application written in coffeescript for node, I have found that I prefer to invert the dependencies, so that each class takes everything it needs in its constructor, like so:
This makes it easy to test each component in isolation, by passing in test doubles (fakes/mocks/spies) where necessary.
Using a container makes it easy to:
For example, we probably only want to send actual email in production, so we would plug in a fake emailer that logs sent emails someplace so we could verify them.
The database configuration also would likely change depending on the environment.
This is how you might configure the above system in Sanders:
Sanders = require 'sanders'container =# you can register constructors# by convention, the names of the argumentis to the constructor# are used to determine the object to passcontainerregisterDatabasecontainerregisterUserRegistrycontainerregisterUserSocket# you can register by name.# these will be matched with constructor arguments with the same name# (case-insensitive)containerregister'logger'ConsoleLoggercontainerregister'websocketconnection'DebugWebSocketConnection# Perhaps you don't want to rely on the argument names,# For example, you want to use a different connection for reports:replicatedDatabaseConnection = server : 'some-other-server'# register the databse with a namecontainerregister'replicatedDatabase'replicatedDatabaseConnection# override the default, just for the user reportcontainerregisterUserReport'replicatedDatabase'# can also register objects directlycontainerregister'databaseConfig'server: 'FOO'user: 'BAR'password : 'BAZ'containerregister'emailConfig'server: 'localhost'fromEmail: 'firstname.lastname@example.org'# now you can get the things you need, with the dependencies you have configureduserSocket = containergetUserSocketuserReport = containergetUserReport
Sanders builds only a single instance of each object. (There is no "lifetime" concept). Each instance is cached for the lifetime of the container.