typedi icon indicating copy to clipboard operation
typedi copied to clipboard

feature: transitional dependency

Open dilame opened this issue 4 years ago • 4 comments

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}}]})

dilame avatar Jan 17 '21 02:01 dilame

Is it that often? If so, can you give me a real-life example, I am interested in learning more.

theodorDiaconu avatar Feb 02 '21 04:02 theodorDiaconu

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 avatar Feb 02 '21 13:02 dilame

@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.

theodorDiaconu avatar Feb 02 '21 15:02 theodorDiaconu

This will be implemented when container inheritance is reworked.

NoNameProvided avatar Feb 13 '21 20:02 NoNameProvided