What is the best way to get the updated value of the tsyringe.register during the runtime?

129 Views Asked by At

I'm wondering is it possible to automatically update the reference to the resolved instance/dependency by the tsyringe container if it had been changed during the runtime?

Basically I'm registering the instance of some class at the beginning

container.register('gqlClient', { useFactory: () => new GqlClientInitial() });

and then I'm resolving it in the constructor of the consumer class

 this.gqlClient = container.resolve('gqlClient');

Then at the runtime I'm creating a new instance and registering it again in the container. However, the reference link isn't automatically updated after it

Here is the code which will demonstrate this issue

Initializer file

class GqlClientInitial {
  query() {
    console.log('initial query');
  }
}

class GqlClient {
  query() {
    console.log('new query');
  }
}

container.register('gqlClient', { useFactory: () => new GqlClientInitial() });

setTimeout(() => {
  container.register('gqlClient', { useFactory: () => new GqlClient() });
}, 10000);

Consumer

import { container, singleton } from 'tsyringe';

@singleton()
export class Repository {
  gqlClient: any;

  constructor() {
    this.gqlClient = container.resolve('gqlClient');
   
  }

  getSomething() {
    // renders: "initial query"
    this.gqlClient.query();

    setTimeout(() => {
     
      // renders: "initial query". But it should render the: "new query"
      this.gqlClient.query();
    }, 15000);
  }

}

It's obvious why it happens because the first assign of the resolved dependency is located in the constructor and after the second register it doesn't refresh the reference from the old instance to the new one

But I'm wondering what is the best way to achieve it? So far, I found only 1 solution: just directly resolve the dependency in the method. For sure, I can create a getter which automatically will be doing it.

getSomething() {
    this.gqlClient.query();

    setTimeout(() => {
      this.gqlClient = container.resolve('gqlClient');
      // renders the: "new query"
      this.gqlClient.query();
    }, 15000);
  }

But I'm not sure if it will be okay if I do this resolving in all the methods and on every method call? Maybe there exists some better approach to solve this issue?

thanks for any info!

0

There are 0 best solutions below