Skip to content

Instantly share code, notes, and snippets.

@alshdavid
Last active January 23, 2021 13:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alshdavid/252a7d0e59885d87e83448f626597651 to your computer and use it in GitHub Desktop.
Save alshdavid/252a7d0e59885d87e83448f626597651 to your computer and use it in GitHub Desktop.
export type Token = string | Symbol
export enum DependencyContainerErrors {
NoDependencyWithToken = 'NoDependencyWithToken'
}
export class DependencyContainer {
private _dependencies: Map<Token, any> = new Map()
public provide(token: Token, dependency: any): void {
this._dependencies.set(token, dependency)
}
public resolve<T = unknown>(token: Token): Promise<T> {
const dependency = this._dependencies.get(token)
if (!dependency) {
throw new Error(DependencyContainerErrors.NoDependencyWithToken)
}
return dependency
}
}
import { DependencyContainer } from 'dependency-container'
import React, { useMemo } from 'react'
// Create the container
const dependencyContainer = new DependencyContainer()
// Define your singleton
const fooToken = Symbol('foo')
class Foo {
public bar() {
alert('Bar!')
}
}
// Add it to your dependency container
dependencyContainer.provide(fooToken, new Foo())
// In your app you can get your dependency container via context
const App = () => {
// Extract from the container the dependency you are looking for
const foo = useMemo(() => dependencyContainer.get(fooToken))
return <button onClick={() => foo.bar}>Foo!</button>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment