A promise-enabled dependency-injection module designed for Synth, but can be used for your own projects.
npm install synth-di
var DI = ;// Create a new dependency systemvar di = ;
What is a service?
A service is a function that can be requested by another service.
They're just ordinary JS functions, except:
- Each service must have a unique name (unique for your app), unless being executed immediately.
- Each service has 0 or more dependencies.
- When a service is executed, Synth-DI will invoke its dependencies first, along with its dependencies' dependencies, and so on.
- A service need not be a function though (I lied earlier). It can also be a named piece of data that is provided at time of execution.
- If a service is not a function, then it can't have any dependencies.
- A service can optionally return a promise. If so, the service won't be considered "ready" until the promise resolves. The result of the promise is then passed in to its caller.
- When a service is executed, a promise is always returned.
- Each service is only called once per execution. So if two services
A and Bdepend on
Cis resolved once and returned to both A and B.
An elaborate Example
Let's say you're writing an Express server and want to fetch some data for an admin user, and then send a response. It needs two things: The user (guaranteed to be an admin), and a connection to the DB.
var DI = ;var di = ;// service name specified as first parameterdi;// The order you register services doesn't matterdi;var dbConnection = processenvMONGO_DB;// service name extracted from given named-functiondi;// Now that we have our services registered, let's get that admin user and data!app;
di.register([optional serviceName:String], [service:Function])
Registers a service/function that can be used by another service/function.
The service name can be specified as the first parameter, or as the name of the function passed in.
di.exec([serviceName:String], [optional services:Object])
Executes the specified service. The requested service should already be registered before executing it.
It returns a promise that then returns the result of the call.
The optional 2nd paramter
An optional 2nd parameter can be provided to provide service dependencies at execution time (overriding already registered services).
The keys are the names of the services, and the values are passed in as those services, untouched.
Unlike a registered service, if a value is a function, it will NOT be invoked first, the function itself will be passed in.