Skip to content

Instantly share code, notes, and snippets.

@kubk

kubk/di-container.ts

Created Jan 18, 2021
Embed
What would you like to do?
import { assert } from "ts-essentials";
export class Container {
private services = new Map<string, object>();
private factories = new Map<string, (container: Container) => object>();
set(key: string, factory: (container: Container) => object) {
this.factories.set(key, factory);
}
get(key: string): object {
if (this.services.has(key)) {
const service = this.services.get(key);
assert(service);
return service;
}
const factory = this.factories.get(key);
assert(factory);
const service = factory(this);
assert(service);
this.services.set(key, service);
return service;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment