Zero dependency IOC container for Node
Installation
npm install ioc-node
Instantiate
// index.js globalioc = __dirname
Usage
Imagine the following class
{ thisdatabase = database }
You can inject dependencies using
ioc
and later make use of the binding with
ioc
If you don't want to create a new instance every time you use ioc.use
, create the binding with ioc.singleton
instead of ioc.bind
.
ioc iocioc // uses same instance
Faking
You can easily fake bindings in your tests!
{ return true } ioc const userService = ioc// assert... ioc // remove the fake again
Global Require
The use
method can also require files globally from any point in the app.
const User = ioc
Automatic Injection
It might be cumbersome to always add bindings, that's why ioc-node also supports automatic injection. Since there are no static types we have to workaround a little to get this working.
Instead of registering bindings in the service provider using ioc.bind('userService', () => new UserService(new Database))
, you can link to the dependency directly in the class
// App/Services/UserService static { return 'path/to/Database' } { thisdatabase = database }
And instead of newing up the class manually, we do
const userService = ioc // will use ioc.use to resolve dependency
or
const UserService = iocconst userService = ioc
You can also pass additional arguments to the constructor
const userService = ioc
Faking Automatic Injection
In the above case, you can still use ioc.fake
to provide a fake database or a fake userService since ioc.make('App/Services/UserService')
uses ioc.use
under the hood. In addition, every auto injected dependencies (e.g. "path/to/Database") also gets resolved using ioc.use
.
Alternatively you can just new up an instance of the class manually.
const UserService = ioc { return true } const userService = )
Aliases
When using ioc.bind
or ioc.singleton
we can access the bindings using the key we provide. Global requires and automatic injections don't provide that flexibility out of the box.
Say the file Cache.js
is inside App/Utils/
. You have to require it using ioc.use('App/Utils/Cache')
, while you might actually want to do ioc.use('Cache')
.
For this you can use aliases.
// in service providerioc // anywhereconst cache = ioc//orconst Cache = ioc
We can also use the alias for automatic injections.
static { return 'Cache' } // ...
How ioc.use resolves dependencies
- Look in fakes (
ioc.fake
) - Look in container (
ioc.bind
/ioc.singleton
) - Look in aliases (
ioc.alias
)- Repeat process with resolved name
- Native require from root of the project
Creating Providers
If you extract code into separate npm modules, you can create a provider that can be easily consumed by the ioc container.
Say you have the following module
{ return value } moduleexports = StringTransformer
In the same module, you can create a provider like this
{ ioc } moduleexports = StringTransformerProvider
and inside the service provider of your app, you can consume this provider
ioc