I'd like to have only one instance of each class per child container.
import "reflect-metadata";
import {injectable, container, singleton} from "tsyringe";
const count = {
bar: 0,
foo: 0,
fao: 0
}
@injectable()
class Foo {
constructor() {
count.foo += 1;
}
public helloWorld() {
console.log("helloworld")
}
}
@injectable()
export class Bar {
constructor(public myFoo: Foo) {
count.bar += 1;
}
}
@injectable()
export class FAO {
constructor(public myFoo: Foo) {
count.fao += 1;
}
}
const create = () => {
const childContainer = container.createChildContainer();
const myBar = childContainer.resolve(FAO);
const other = childContainer.resolve(Bar);
}
create();
create();
I d like to have a "singleton" within my childcontainer. All classes would be instanciated only once per child container. @singleton is resolved only within global container.
How can I do this?
There is a method registerSingleton
within a child container
const childContainer= container.createChildContainer();
childContainer.registerSingleton(Foo);
childContainer.resolve(Bar)