如何创建一个注入和一个const实例?

时间:2016-12-12 16:57:21

标签: typescript inversifyjs

A的实例需要获取类O的实例的依赖关系,而不是其他实例的单例。怎么做?

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

1 个答案:

答案 0 :(得分:1)

无法在文档中找到它,但此处建议的ide是一个选项 -

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