Created
January 18, 2021 11:20
-
-
Save kubk/6457de061b167e0a52026e5e547b5db3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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