简体   繁体   中英

How to fix InversifyJs too much recursion error

This is my first time I implement InversifyJs from scratch. This is a new concept for me to be honest.

I am trying to inject a class A in a class B and vice-versa. Class B In class A . But Inversify does not look happy and returns and error too much recursion .

Here is an example here in CodeSandbox.

I tried to follow the documentation as well in the section of Circular dependencies , but it looks like I am doing something wrong ? Maybe ?

If anyone is looking for something similar, to solve this issue you need to use factories. See this example here . This topic was useful too

const myContainer = new Container();
  myContainer.bind<IB>(TYPES.B).to(B).inSingletonScope(); // B is the Child
  myContainer.bind<IA>(TYPES.A).to(A).inSingletonScope(); // A is the Parent
  // The magic below !
  myContainer.bind<FactoryB>(TYPES.BFactory).toFactory<IB>(
      (ctx: interfaces.Context) => (parent: IA) => {
        const b = ctx.container.get<IB>(TYPES.B);
        b.setParent(parent); // setter of parent A in B
        return b;
      }
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM