typescript-ioc icon indicating copy to clipboard operation
typescript-ioc copied to clipboard

Async Factory

Open davidbayo10 opened this issue 4 years ago • 5 comments

Hi all! I want to perform this factory class behaviour, but when I call new S(), a promise is returned. Do I do something wrong? May this feature is not present for being used as factory?

const factory: ObjectFactory = async () => S.getInstance();

@Factory(factory)
export class S {

  private static _instance: S;

  static async getInstance(): Promise<S> {
    if (!this._instance) {
      this._instance = new S();

      await this._instance.createClient();
    }

    return this._instance;
  }

  async createClient(): Promise<void> {
    this._client = await createClientAsync('url');
  }

}

Thank you all in advance!

davidbayo10 avatar Apr 21 '20 12:04 davidbayo10

Just had the same problem. You'll get a Promise if you use it like this. I solved it like this

const messenger = await Messenger.create(uri, serviceName, ttl)
Container
		.bind(Messenger)
		.factory(() => messenger)
		.scope(Scope.Singleton)

Works for me because im in a async function while using await

InsOpDe avatar Aug 03 '20 13:08 InsOpDe

Any update on this ?

TheOnlyMrFlow avatar Feb 02 '21 13:02 TheOnlyMrFlow

Just had the same problem. You'll get a Promise if you use it like this. I solved it like this

const messenger = await Messenger.create(uri, serviceName, ttl)
Container
		.bind(Messenger)
		.factory(() => messenger)
		.scope(Scope.Singleton)

Works for me because im in a async function while using await

I prefer to use @Inject into property classes

davidbayo10 avatar Feb 02 '21 13:02 davidbayo10

Any update on this ?

I think this repo is not maintained...

davidbayo10 avatar Feb 02 '21 13:02 davidbayo10

I'm using async-injection instead of this one.

tripodsgames avatar Jul 02 '21 14:07 tripodsgames