DI:类的构造函数可注入如何调用服务器时间

时间:2019-05-29 15:45:18

标签: typescript inversifyjs

有几个类,如何注入TermsExchangeService

import {TermsExchangeService} from './terms-exchange.service';

@injectable()
export class TermsExchangeComponent {
  constructor(
        private termsExchangeService: TermsExchangeService
    ) {}
}

import {TermsExchangeService} from './terms-exchange.service';

@injectable()
export class PurchaseMainComponent {
    constructor(
       private termsExchangeService: TermsExchangeService
    ) {}

以及如何在PurchaseMainComponentTermsExchangeComponent中使用

@injectable()
export class TermsExchangeService {

    constructor() {
        debugger; // call 2 times!!!
    }
}

我使用autoBindInjectable

var simpleContainer = new Container({ autoBindInjectable: true })

TermsExchangeService的循环构造函数获取组件时,需要多次调用:

for (let item = 0; item < components.length; item++) {
   const container = simpleContainer.get(components[item]);
}

为什么在每个组件中创建对象?以及如何进行正常注射?

1 个答案:

答案 0 :(得分:0)

默认情况下,injectable不是Singleton。

解决此问题可以添加defaultScope: 'Singleton'

var simpleContainer = new Container(
            { 
               autoBindInjectable: true, 
               defaultScope: 'Singleton'
            }
)