dik
A small dependency-injection container with
Promise
support
Installation
$ npm install --save dik
Dik requires an ES5-compatible environment and a native (globally available)
Promise
. It is recommended to use babel.
Example
A simple example of server-side React rendering with express and react-router.
Although Dik
is isomorphic, the example below is only half (arguably not
that interesting half) of what it can do. A more involved example with
client- and server-side Flux is coming soon.
start.js
di
index.js
const di =
app.js
{ return } { const app = app return app}
routes.js
const Route DefaultRoute RouteHandler = Router const App = React const Main = React const About = React { return <Route handler=App path="/"> <DefaultRoute handler=Main /> <Route name="about" handler=About path="about" /> </Route> }
Contributing
Issues and pull requests are welcomed. For code style, please use
editorconfig and jshint
.
Running tests
$ git clone https://github.com/zaim/dik.git
$ npm install
$ npm test
Prior Art
Dik was inspired by Cation and create-container.
Cation
is a fully customizable DIC with Promises/async support. If you need
custom resource providers (e.g. Factories, Services, Static), use Cation.
create-container
on the other hand is a minimal application container,
but without Promises/async. If you don't want or need asynchronous support,
use create-container.
License
Dik is released under the MIT license.
API
Dik
The Dik container class.
Example
const dik =
Dik#register(id, fn, options)
Register a resource provider
The options
argument can be an options object,
which may have these properties:
-
deps
- array of resource provider ID strings that this resource is dependent upon. -
factory
- boolean, if true the resource will not be cached and a new instance is returned on everyget
call.
As a shortcut, the array of ID strings can also be
passed directly as the options
argument.
A special resource id $get
can be specified to
get access to the Dik#get
method in the resource
provider function in order to look-up other resources
(see example below)
Parameters
parameter | type | description |
---|---|---|
id |
string | The unique ID to register the resource as |
fn |
function | The resource provider function |
options |
object | optional: Options object or array of dependency IDs |
Example
// Simple resource provider:dik // Specify dependencies in options object:dik // Specify dependencies in directly:dik // Lookup other resources:dik
Returns Dik
, self
Dik#get(id)
Look up a registered resource and its dependencies
Parameters
parameter | type | description |
---|---|---|
id |
string | The registered resource provider's ID |
Example
dik
Returns Promise
, A Promise for the created resource object