How to fix InversifyJs too much recursion error

181 views Asked by At

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 ?

1

There are 1 answers

0
Zied Hf On

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