@squirly/di
v0.4.0
Published
A slim, fully typed dependency inection library for achieving IoC.
Downloads
23
Readme
@squirly/di
A slim, fully typed, asynchronous dependency injection library for achieving IoC.
TODO: Fill out this long description.
Table of Contents
Install
npm install @squirly/di
Usage
Container
import {Binding, Container, Injectable} from '@squirly/di';
const AuthenticationKey = Binding<string>('AuthenticationKey');
interface Fetcher {
fetch: () => Promise<{data: string}>;
}
const Fetcher = Binding<Fetcher>('Fetcher');
@Injectable
class Client {
static Tag = Binding.Tag<Client>('Client');
static Inject = Injectable.Resolution(Fetcher);
constructor(private readonly fetcher: Fetcher) {}
getData(): Promise<string> {
return this.fetcher
.fetch()
.then(result => `Received result: '${result.data}'`);
}
}
async function fetcherFactory(c: Container<string>): Promise<Fetcher> {
const key = await c.resolve(AuthenticationKey);
return {
fetch: () =>
Promise.resolve({
data: `Called with AuthenticationKey "${key}"`,
}),
};
}
const container = Container.create()
.bindConstant(AuthenticationKey, 'my-secret-key')
.bindSingletonFactory(Fetcher, fetcherFactory)
.bindService(Client, Client);
const clientResult = container.resolve(Client).then(client => client.getData());
// Logs 'Received result: Called with AuthenticationKey "my-secret-key"';
clientResult.then(console.log);
Module
Using the definitions above, a Module
can be created.
import {Module} from '@squirly/di';
const module = Module.create(
Container.create()
.bindConstant(AuthenticationKey, 'my-secret-key')
.bindSingletonFactory(Fetcher, fetcherFactory),
).export(Fetcher);
const moduleContainer = Container.create()
.importModule(module)
.bindService(Client, Client);
moduleContainer.resolve(Client).then(client => {
client.getData(); // returns "Calling API with 'yek-terces-ym'"
});
// $ExpectError
const resolution = moduleContainer.resolve(AuthenticationKey);
// Type 'string' is not assignable to 'Fetcher | Client'
// Logs "MissingDependencyError('Could not find dependency bound to AuthenticationKey.')"
clientResult.catch(console.log);
Maintainers
Tyler Jones ~ @squirly
Contribute
PRs accepted. Commits must follow the Angular Commit Message Conventions.
If editing the README, please conform to the standard-readme specification.
License
MIT © 2018 Tyler David Jones