README
Containor
Deprecated in favor ofA lightweight dependency injector for Javascript.
Inject.js weighs just ~2kb minified and has no dependencies!
Guide
- Installation
- Registering dependencies
- Resolving dependencies
- Lazy resolving
- Resetting
- Mocking (Unit testing)
Installation
npm install inject.js
Usage as a module
var injector = require('inject.js')
Usage directly in browser
To use directly in the browser, you can use the packaged version. This will make the injector globally available.
Do not use this version in nodejs or when you bundle your application!
<script src="node_modules/inject.js/dist/inject.min.js"></script>
<!-- For debugging or testing -->
<script src="node_modules/inject.js/dist/inject.js"></script>
Registering dependencies
Register a dependency with injector.register
. The name must be a valid string, the dependency itself can by anything. You cannot register the same name twice.
var someDependency = require('./some-dependency')
injector.register('someDependency', { someMethod: 'abc' })
It's recommended to use valid variable names as a name. This is handy when resolving multiple dependencies.
Resolving dependencies
Elsewhere import the injector and get the dependency with injector.resolve(name)
var someDependency = injector.resolve('someDependency')
Resolving multiple dependencies
Providing an array to injector.resolve
will return an object with the dependency names as keys and dependencies as values.
var dependencies = injector.resolve([ 'someDependency', 'otherDependency' ])
// Accessing dependencies:
dependencies.someDependency
dependencies.otherDependency
// Using ES6
const { someDependency, otherDependency } = injector.resolve([
'someDependency',
'otherDependency'
])
Lazy resolving
Lazy resolving is useful when you are in an environment (like the browser) where scripts might be loaded async. Could also let your app be more flexible about the load order of scripts. You provide the dependencies you need to wait for and a callback that is called when all dependencies are resolved. The callback is called with the dependencies as arguments.
injector.lazy(['depA', 'depB'], runApp)
function runApp(depA, depB) {
// Do your thing :)
}
Resetting
Run injector.reset()
to remove all dependencies.
injector.reset()
Mocking (Only use for unit testing!)
With injector.mock(name, mockDependency)
you can mock a dependency for unit testing. It works the same as injector.register
, only if a dependency already exists, injector.mock
will override it.
If process.env.NODE_ENV is set to production or in the minified packaged version, mock will not be available. This is to prevent it's usage outside of unit testing
injector.mock('someDependency', { test: 'test' })