0

An instance of class A needs to obtain the dependence of an instance of a class O, but to be singletons for others. How to do it?

@injectable()
class O{}

// A must be single instance!
@injectable()
class A{
    constructor(o: O){
        console.log( 'is A instance' );
    }
}
@injectable()
class B{
    constructor(a: A){
        console.log( 'is B instance' );
    }
}
@injectable()
class C{
    constructor(a: A){
        console.log( 'is C instance' );
    }
}
@injectable()
class D{
    constructor(b: B, c: C){
        console.log( 'is D instance' );
    }
}


let container = new Container();
container.bind<B>( O ).to( O );
container.bind<B>( A ).toConstantValue( A ); // ?
container.bind<B>( B ).to( B );
container.bind<C>( C ).to( C );
container.bind<D>( D ).to( D );

container.get<D>(D);
user220409
  • 184
  • 1
  • 17

1 Answers1

2

Couldn't find it in the documentation, but the ide suggested here is an option -

@injectable()
class O{}

// A must be single instance!
@injectable()
class A{
    constructor(o: O){
        console.log( 'is A instance' );
    }
}
@injectable()
class B{
    constructor(a: A){
        console.log( 'is B instance' );
    }
}
@injectable()
class C{
    constructor(a: A){
        console.log( 'is C instance' );
    }
}
@injectable()
class D{
    constructor(b: B, c: C){
        console.log( 'is D instance' );
    }
}


let container = new Container();
container.bind<O>( O ).to( O );
container.bind<A>( A ).to( A ).inSingletonScope();
container.bind<B>( B ).to( B );
container.bind<C>( C ).to( C );
container.bind<D>( D ).to( D );

container.get<D>(D);
user220409
  • 184
  • 1
  • 17