Given that there is finite amount of instances, the straightforward way may be:
@Component({
providers: [
{ provide: 'TestService1', useClass: TestService },
{ provide: 'TestService2', useClass: TestService }
]
})
export class TestComponent implements OnInit {
constructor(
@Inject('TestService1') private _testService1: TestService,
@Inject('TestService2') private _testService2: TestService
) {}
...
}
Or OpaqueToken
counterpart to avoid overriding services with the same string identifier:
export const TestService1 = new OpaqueToken;
export const TestService2 = new OpaqueToken;
...
providers: [
{ provide: TestService1, useClass: TestService },
{ provide: TestService2, useClass: TestService }
]
...
constructor(
@Inject(TestService1) private _testService1: TestService,
@Inject(TestService2) private _testService2: TestService
) {}
It doesn't hurt DI in TestService
constructor. And keeps the testability of TestComponent
on par, both service instances can be mocked independently.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…