typedi
typedi copied to clipboard
question: Idiomatic usage of scoped value (per-container) in a single .get call
I was trying to...
Register a Token value that could be reused in all resolved instanced per call to Container.get(MyService)
use case: a correlation or commonId UUID that's shared between logger and service and repository
The problem:
I can achieve only by creating a scoped container, using Container.get(MyService won't share the REQUEST_ID_TOKEN
// code below works but I crate always a new `scopedContainer`, not sure that can cause memory leaks or any other issues
/* trimmed for brevity */
export function getScopedContainer(scopeName?: string): ContainerInstance {
const scopedContainer = Container.of(scopeName)
scopedContainer.set({
id: 'version',
factory: () => {
return '42.0.0
},
})
scopedContainer.set({
id: REQUEST_ID_TOKEN,
factory: () => v4(),
})
scopedContainer.set(Logger, new Logger((scopedContainer as any) as ContainerInstance))
scopedContainer.set(TogglesService, new TogglesService(defaultToggles))
scopedContainer.set(Endpoints, new Endpoints((scopedContainer as any) as ContainerInstance))
scopedContainer.set(
StoriesService,
new StoriesService((scopedContainer as any) as ContainerInstance)
)
return scopedContainer
}