Skip to content

Instantly share code, notes, and snippets.

@kubk
Created January 18, 2021 11:20
Show Gist options
  • Save kubk/6457de061b167e0a52026e5e547b5db3 to your computer and use it in GitHub Desktop.
Save kubk/6457de061b167e0a52026e5e547b5db3 to your computer and use it in GitHub Desktop.
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