InversifyJS icon indicating copy to clipboard operation
InversifyJS copied to clipboard

@preDestroy() gets called multiple times on the same instance when it has other bindings pointing to it

Open Nikitakun opened this issue 4 years ago • 0 comments

I would expect @preDestroy() to be called just once per instance it's bound to, however when there's other toService() bindings pointing to it, it will be called as many times as there are bindings attached to it which could lead to unpleasant consequences. Is there a way to bypass it using this decorator?

@injectable()
class Test1 {

  @preDestroy()
  public destroy() {
    console.log('Destroy!!!');
  }

}

@injectable()
class Test2 implements Test1 {

  destroy(): void { }

}

@injectable()
class Test3 implements Test1 {

  destroy(): void { }

}

const c = new Container({ defaultScope: 'Singleton' });

c.bind(Test1).toSelf();
c.bind(Test2).toService(Test1);
c.bind(Test3).toService(Test1);

c.get(Test1);
c.get(Test2);
c.get(Test3);

c.unbindAll();
// (3) Destroy!!! (called three times)

Nikitakun avatar Jan 07 '22 10:01 Nikitakun