# q-di

> Asynchronous dependency injection using Q promises

Latest version **0.2.1** (published 2014-01-12) · MIT license · 0 weekly downloads

## Install

```sh
npm install q-di
pnpm add q-di
yarn add q-di
bun add q-di
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.2.1 |
| Published | 2014-01-12 |
| First published | 2014-01-01 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 2 |
| Known vulnerabilities | 0 (+5 in 1 direct dependencies) |
| Install scripts | no |
| Maintainers | allenc |
| Keywords | di, dependency, injector, injection, q, async, promise |

## Links

- npm: https://www.npmjs.com/package/q-di
- Repository: https://github.com/allenc256/q-di
- Issues: https://github.com/allenc256/q-di/issues
- npm.io page: https://npm.io/package/q-di

## Dependencies (2)

- [q](https://npm.io/package/q.md) ~0.9.7
- [lodash](https://npm.io/package/lodash.md) ~2.4.1

## Alternatives

- [memory-cache](https://npm.io/package/memory-cache.md) — 795.0K weekly downloads
- [@httptoolkit/proxy-agent](https://npm.io/package/@httptoolkit/proxy-agent.md) — 11.2K weekly downloads
- [express-cache-controller](https://npm.io/package/express-cache-controller.md) — 5.3K weekly downloads
- [http-cache-middleware](https://npm.io/package/http-cache-middleware.md) — 4.5K weekly downloads
- [cache2](https://npm.io/package/cache2.md) — 1.5K weekly downloads

## Recent versions

- 0.2.1 (latest) — 2014-01-12
- 0.2.0 — 2014-01-12
- 0.1.6 — 2014-01-07
- 0.1.5 — 2014-01-07
- 0.1.4 — 2014-01-06
- 0.1.3 — 2014-01-06
- 0.1.2 — 2014-01-06
- 0.1.1 — 2014-01-02
- 0.1.0 — 2014-01-01

## README

q-di
====

Dependency injection capable of handling asynchronous dependencies using the promise library [Q](http://github.com/kriskowal/q). Some inspiration drawn from the Java DI frameworks [Guice](https://code.google.com/p/google-guice/) and [Dagger](http://square.github.io/dagger/).

## How to use

A set of dependencies (henceforth referred to as a "module") is specified via a Javascript object. Each dependency is a named function. The arguments of the function specify the prerequisite dependencies that must be satisfied before the dependency itself can be satisfied. A module for a hypothetical server might look like (source code in [CoffeeScript](http://coffeescript.org/) for succinctness):

```coffee
MODULE = {
  server  : (cache, database) -> new MyServer(cache, database)
  cache   : -> new MyCache()
  database: -> new MyDatabase()
}
```

Here we see that constructing a `server` object depends on first constructing a `cache` object and a `database` object. To actually construct a `server` object, we need to create an `Injector` and call the correspondingly named function on it:

```coffeescript
di = require('q-di')
injector = new di.Injector(MODULE)
injector.server() # construct a server (returns a Q promise)
```

### Promises/asynchrony

Dependencies can return promises instead of raw values. For example, the following module introduces a 100 ms delay when constructing a `foo` object:

```coffeescript
MODULE = {
  foo : -> Q.delay(100).then(-> 'foo')
}

# Prints "foobar" (after 100 ms):
new di.Injector(MODULE).foo().done((result) -> console.log(result))
```

The above example is contrived, but more realistically, some of your components may need to perform IO asynchronously before they are fully initialized. For example, your `server` object might depend on a `database` object which needs to first establish a connection to the database before it's initialized.

### Explicit argument names

Names of dependency arguments can also be specified explicitly, as shown below. This method for specifying dependencies might be useful if you want to use periods in your dependency names (e.g., to namespace things, such as 'server.backend.cache'):

```coffeescript
MODULE = {
  server: {
    args   : ['services.cache', 'services.database']
    create : (c, d) -> new MyServer(c, d)
  }
  # ...
}
```

### Hierarchical dependencies

Dependency names containing periods ('.') can be treated hierarchically if the `hierarchical` flag is set to `true`, as below:

```coffeescript
MODULE = {
  'services.component1' : -> new MyComponent1()
  'services.component2' : -> new MyComponent2()
  'services.component3' :
    args   : ['services.component1', 'services.component2']
    create : (c1, c2) -> new MyComponent3(c1, c2)
}

injector = new di.Injector(MODULE, { hierarchical: true })

# Returns promise for services "container object" containing the 3 components.
injector.services()

# Returns promise for component 1.
injector['services.component1']()
```

This introduces implicit "container object" dependencies into the created injector which will automatically create all dependencies within the container when invoked. Containers can be nested arbitrarily deep:

```coffeescript
injector = new di.Injector({
  'foo.bar.baz' : -> ...
}, { hierarchical: true })

# Returns promise for bar container.
injector.foo().then -> foo.bar

# Also returns promise for bar container.
injector['foo.bar']() 
```

This is another feature which can be useful when organizing larger codebases.

## Notes

### Scoping

All constructed objects are singleton-scoped to the injector. This means that calling a method on an injector multiple times will return the same instance of the object (actually, promise), e.g. the following returns true:

```coffeescript
injector.foo() == injector.foo() # always equal
```

Objects are not shared across injectors, however, e.g. if injector1 and injector2 are separate objects:

```coffeescript
injector1.foo() != injector2.foo() # never equal
```

### Cycles

Cyclic dependencies will result in an error being thrown, e.g. the following fails:

```coffeescript
new di.Injector({ foo: (foo) -> }).foo() # throws error
```

### Promise coercion

The Q library is compatible with many other promise implementations (as long as they follow the [Promises/A+ specification](http://promises-aplus.github.io/promises-spec/)). This means module dependencies may return non-Q promises. Note, however, that the injector will always coerce such promises into Q promises.

---
_Source: https://npm.io/package/q-di · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
