Last active
January 23, 2021 13:10
-
-
Save alshdavid/252a7d0e59885d87e83448f626597651 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
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 | |
} | |
} |
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 { 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