allow to create the instantiation service with a strict flag such that it throw on missing services, #5653

This commit is contained in:
Johannes Rieken
2016-04-23 18:56:46 +02:00
parent a6d74034f1
commit d6105f2f1f
2 changed files with 18 additions and 14 deletions
@@ -19,9 +19,11 @@ export class InstantiationService implements IInstantiationService {
serviceId: any;
private _services: ServiceCollection;
private _strict: boolean;
constructor(services: ServiceCollection = new ServiceCollection()) {
constructor(services: ServiceCollection = new ServiceCollection(), strict: boolean = false) {
this._services = services;
this._strict = strict;
this._services.set(IInstantiationService, this);
}
@@ -32,7 +34,7 @@ export class InstantiationService implements IInstantiationService {
services.set(id, thing);
}
});
return new InstantiationService(services);
return new InstantiationService(services, this._strict);
}
invokeFunction<R>(signature: (accessor: ServicesAccessor, ...more: any[]) => R, ...args: any[]): R {
@@ -113,9 +115,9 @@ export class InstantiationService implements IInstantiationService {
let serviceDependencies = _util.getServiceDependencies(desc.ctor).sort((a, b) => a.index - b.index);
let serviceArgs = serviceDependencies.map(dependency => {
let service = this._getOrCreateServiceInstance(dependency.id);
// if (!service && !dependency.optional) {
// throw new Error(`[createInstance] ${desc.ctor.name} depends on UNKNOWN service ${dependency.id}.`);
// }
if (!service && this._strict && !dependency.optional) {
throw new Error(`[createInstance] ${desc.ctor.name} depends on UNKNOWN service ${dependency.id}.`);
}
return service;
});
let firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : staticArgs.length;
@@ -87,12 +87,12 @@ class TargetWithStaticParam {
}
}
class TargetOptional1 {
class TargetNotOptional {
constructor( @IService1 service1: IService1, @IService2 service2: IService2) {
assert.ok(false, 'should not be here');
}
}
class TargetOptional2 {
class TargetOptional {
constructor( @IService1 service1: IService1, @optional(IService2) service2: IService2) {
assert.ok(service1);
assert.equal(service1.c, 1);
@@ -200,13 +200,15 @@ suite('Instantiation Service', () => {
});
test('@Param - optional', function () {
let collection = new ServiceCollection();
let service = new InstantiationService(collection);
collection.set(IService1, new Service1());
// service.addSingleton(IService2, new Service2());
let collection = new ServiceCollection([IService1, new Service1()]);
let service = new InstantiationService(collection, true);
// assert.throws(() => service.createInstance(TargetOptional1));
service.createInstance(TargetOptional2);
service.createInstance(TargetOptional);
assert.throws(() => service.createInstance(TargetNotOptional));
service = new InstantiationService(collection, false);
service.createInstance(TargetOptional);
service.createInstance(TargetNotOptional);
});
// we made this a warning