extremely thin async dependency injection
Extremely thin, async dependency injection, now with a getting started guide.
Inspired by Google’s Guice library and written in Typescript.
Consider a Server
class that needs to fetch data from the Cache
and Filesystem
, but doesn’t know (or need to
know) how those are implemented.
import { Cache, Filesystem } from './interfaces';
import { LocalModule } from './local';
import { NetworkModule } from './network';
@Inject(Cache, Filesystem)
class Server {
protected readonly cache: Cache;
protected readonly filesystem: Filesystem;
protected readonly ttl: number;
constructor(options) {
this.cache = options.cache;
this.filesystem = options.filesystem;
this.ttl = defaultTo(options.ttl, 0);
}
get(path: string) {
return options.cache.get(path, this.ttl, () => options.filesystem.get(path));
}
}
function module() {
if (process.env['DEBUG'] === 'TRUE') {
return new LocalModule();
} else {
return new NetworkModule();
}
}
async function main() {
const container = Container.from(module());
await container.configure();
const foo = await container.create(Server, {
/* cache and filesystem are found and injected by container */
ttl: 60,
});
}
noicejs will collect dependencies from the decorated constructor and any superclasses, find a provider for each injected dependency, and asynchronously resolve them before calling the constructor. Any extra parameters are passed on to the original constructor, along with the container and resolved dependencies.
To build a bundle and run tests:
> make
yarn
yarn install v1.17.3
[1/4] Resolving packages...
success Already up-to-date.
Done in 0.20s.
/home/ssube/code/ssube/noicejs//node_modules/.bin/rollup --config /home/ssube/code/ssube/noicejs//config/rollup.js
src/index.ts, test/harness.ts, test/**/Test*.ts → out/...
...
created out/ in 3.3s
/home/ssube/code/ssube/noicejs//node_modules/.bin/api-extractor run --config /home/ssube/code/ssube/noicejs//config/api-extractor.json --local -v
api-extractor 7.3.8 - https://api-extractor.com/
...
API Extractor completed successfully
Success!