typedi
typedi copied to clipboard
feature: transitional dependency
Description
It is often needed to pass one-time options to an instance as a temporary dependency.
Proposed solution
container.get(SomeClass, {providers: [{id: SomeToken, value: {option: 123}}]})
container.get(SomeClass, {providers: [{id: SomeToken, value: {option: 321}}]})
Is it that often? If so, can you give me a real-life example, I am interested in learning more.
It's very often when you developing and DI-based SDK. My real-life example - i am using playwright. My facade looks like this
sdk.media('media-id-here')
It creates MediaPage
class instance
@Service({ transient: true, global: true })
export class MediaPage implements IgpapiPage {
constructor(private page: Page, private state: State) {}
async inverseLike() {
await this.page.click('article section:first-child button');
}
}
Page
is playwright
web page class instance, it is the transient dependency - i need to pass new Page
instance for every media id. But State
is the permanent dependency - it's SDK internal state.
And i got a lot of such cases in my SDK. Now i solve it like this
this.container.set(Page, page);
const classObj = this.container.get(cls);
this.container.remove(Page);
@dilame I get it, I had the same situation, the way I did is via factory function from a global "store". It felt easier this way, but I agree I was instantiating my new class in that factory function instead of using dependency injection. Kinda "opted-out" of it.
This will be implemented when container inheritance is reworked.