DI:class 的构造函数如何多次调用 injectable
DI: constructor of class how injectable calls serveral times
有几个类,怎么注入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
) {}
和服务如何在PurchaseMainComponent
和TermsExchangeComponent
中使用
@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]);
}
为什么在每个组件中创建对象?以及如何正常注射?
默认情况下 injectable
不是单例。
解决这个问题可以加上defaultScope: 'Singleton'
:
var simpleContainer = new Container(
{
autoBindInjectable: true,
defaultScope: 'Singleton'
}
)
有几个类,怎么注入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
) {}
和服务如何在PurchaseMainComponent
和TermsExchangeComponent
@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]);
}
为什么在每个组件中创建对象?以及如何正常注射?
默认情况下 injectable
不是单例。
解决这个问题可以加上defaultScope: 'Singleton'
:
var simpleContainer = new Container(
{
autoBindInjectable: true,
defaultScope: 'Singleton'
}
)