@romain-faust/provy
Simple and versatile dependency container.
Installation
With NPM:
npm install @romain-faust/provy
With PNPM:
pnpm add @romain-faust/provy
With Yarn:
yarn add @romain-faust/provy
Usage
import { buildContainer, buildKey } from '@romain-faust/provy'
const keys = {
apiService: buildKey<ApiService>('API_SERVICE'),
apiUrl: buildKey<string>('API_URL'),
}
const container = buildContainer()
container.registerMemoized(keys.apiService, (container) => {
return buildApiService(container.resolve(keys.apiUrl))
})
container.registerConstant(keys.apiUrl, 'https://api.example.com')
// ...
container.resolve(keys.apiService)
API
buildContainer(parent?: Container)
Builds a new Container
. The parent
parameter can be used to specify the Container
to use to resolve dependencies if they don't exist in the current one.
buildKey(name: string)
Builds a new Key
. The name
parameter is used to identify keys (it is NOT expected to be unique).
Container
Holds the dependencies registry.
.isRegistered(key)
Checks if the given Key
is registered.
.registerAlias(keyA, keyB)
Registers an alias to another dependency.
.registerConstant(key, value)
Registers a constant.
.registerDynamic(key, factory)
Registers a factory function. The result isn't memoized meaning that the factory
function is called whenever the dependency is requested.
.registerMemoized(key, factory)
Registers a factory function. The factory
function is called only once and its result is then memoized and reused on subsequent calls.
.resolve(key)
Retrieves the dependency associated to the given key
. If there is no dependency registered an error is thrown.
.unregister(key)
Unregisters the dependency associated to the given key
.
Key<T>
Identifies a dependency within a Container
. It accepts a generic parameter T
which is used to type values resolved from Container
.