typedi icon indicating copy to clipboard operation
typedi copied to clipboard

fix: multiple instance created when using scoped container with circular references

Open icedcrow opened this issue 4 years ago • 0 comments

I have A and B injecting each other:

import "reflect-metadata";
import { Container, Inject, Service } from "typedi";


@Service()
class A {
  @Inject((type) => B)
  private b!: B;

  constructor() {
    console.log("a constructor");
  }

  aaa() {
    console.log("aaa");
    this.b.bbb();
  }

  abc() {
    console.log("abc");
  }
}

@Service()
class B {
  @Inject((type) => A)
  private a!: A;

  constructor() {
    console.log("b constructor");
  }

  bbb() {
    console.log("bbb");
    this.a.abc();
  }
}

@Service()
class Test {
  @Inject((type) => A)
  private a!: A;

  constructor() {
    console.log("test constructor");
  }

  do() {
    console.log("do");
    this.a.aaa();
  }
}

everything goes well when using global container:

Container.get(Test).do();

// test constructor 
// a constructor 
// b constructor 
// do 
// aaa 
// bbb 
// abc 

created multiple times when using scoped container:

Container.of("str").get(Test).do();

// test constructor 
// a constructor 
// b constructor 
// a constructor 
// b constructor 
// do 
// aaa 
// bbb 
// abc 

codesandbox

icedcrow avatar Apr 16 '21 08:04 icedcrow