refactor(core): separate reflective injector from Injector interface
BREAKING CHANGE: - Injector was renamed into `ReflectiveInjector`, as `Injector` is only an abstract class with one method on it - `Injector.getOptional()` was changed into `Injector.get(token, notFoundValue)` to make implementing injectors simpler - `ViewContainerRef.createComponent` now takes an `Injector` instead of `ResolvedProviders`. If a reflective injector should be used, create one before calling this method. (e.g. via `ReflectiveInjector.resolveAndCreate(…)`.
This commit is contained in:
parent
efbd446d18
commit
0a7d10ba55
@ -1,4 +1,10 @@
|
|||||||
import {Inject, Injector, forwardRef, resolveForwardRef, ForwardRefFn} from 'angular2/core';
|
import {
|
||||||
|
Inject,
|
||||||
|
ReflectiveInjector,
|
||||||
|
forwardRef,
|
||||||
|
resolveForwardRef,
|
||||||
|
ForwardRefFn
|
||||||
|
} from 'angular2/core';
|
||||||
|
|
||||||
// #docregion forward_ref_fn
|
// #docregion forward_ref_fn
|
||||||
var ref = forwardRef(() => Lock);
|
var ref = forwardRef(() => Lock);
|
||||||
@ -13,7 +19,7 @@ class Door {
|
|||||||
// Only at this point Lock is defined.
|
// Only at this point Lock is defined.
|
||||||
class Lock {}
|
class Lock {}
|
||||||
|
|
||||||
var injector = Injector.resolveAndCreate([Door, Lock]);
|
var injector = ReflectiveInjector.resolveAndCreate([Door, Lock]);
|
||||||
var door = injector.get(Door);
|
var door = injector.get(Door);
|
||||||
expect(door instanceof Door).toBe(true);
|
expect(door instanceof Door).toBe(true);
|
||||||
expect(door.lock instanceof Lock).toBe(true);
|
expect(door.lock instanceof Lock).toBe(true);
|
||||||
|
@ -11,7 +11,7 @@ import {
|
|||||||
} from 'angular2/src/facade/lang';
|
} from 'angular2/src/facade/lang';
|
||||||
import {StringMapWrapper} from 'angular2/src/facade/collection';
|
import {StringMapWrapper} from 'angular2/src/facade/collection';
|
||||||
import {BaseException} from 'angular2/src/facade/exceptions';
|
import {BaseException} from 'angular2/src/facade/exceptions';
|
||||||
import {NoAnnotationError} from 'angular2/src/core/di/exceptions';
|
import {NoAnnotationError} from 'angular2/src/core/di/reflective_exceptions';
|
||||||
import * as cpl from './compile_metadata';
|
import * as cpl from './compile_metadata';
|
||||||
import * as md from 'angular2/src/core/metadata/directives';
|
import * as md from 'angular2/src/core/metadata/directives';
|
||||||
import * as dimd from 'angular2/src/core/metadata/di';
|
import * as dimd from 'angular2/src/core/metadata/di';
|
||||||
@ -27,7 +27,11 @@ import {PLATFORM_DIRECTIVES, PLATFORM_PIPES} from 'angular2/src/core/platform_di
|
|||||||
import {MODULE_SUFFIX} from './util';
|
import {MODULE_SUFFIX} from './util';
|
||||||
import {assertArrayOfStrings} from './assertions';
|
import {assertArrayOfStrings} from './assertions';
|
||||||
import {getUrlScheme} from 'angular2/src/compiler/url_resolver';
|
import {getUrlScheme} from 'angular2/src/compiler/url_resolver';
|
||||||
import {Provider, constructDependencies, Dependency} from 'angular2/src/core/di/provider';
|
import {Provider} from 'angular2/src/core/di/provider';
|
||||||
|
import {
|
||||||
|
constructDependencies,
|
||||||
|
ReflectiveDependency
|
||||||
|
} from 'angular2/src/core/di/reflective_provider';
|
||||||
import {
|
import {
|
||||||
OptionalMetadata,
|
OptionalMetadata,
|
||||||
SelfMetadata,
|
SelfMetadata,
|
||||||
@ -185,7 +189,7 @@ export class RuntimeMetadataResolver {
|
|||||||
|
|
||||||
getDependenciesMetadata(typeOrFunc: Type | Function,
|
getDependenciesMetadata(typeOrFunc: Type | Function,
|
||||||
dependencies: any[]): cpl.CompileDiDependencyMetadata[] {
|
dependencies: any[]): cpl.CompileDiDependencyMetadata[] {
|
||||||
var deps: Dependency[];
|
var deps: ReflectiveDependency[];
|
||||||
try {
|
try {
|
||||||
deps = constructDependencies(typeOrFunc, dependencies);
|
deps = constructDependencies(typeOrFunc, dependencies);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
@ -31,8 +31,11 @@ export function getPropertyInView(property: o.Expression, viewPath: CompileView[
|
|||||||
|
|
||||||
export function injectFromViewParentInjector(token: CompileTokenMetadata,
|
export function injectFromViewParentInjector(token: CompileTokenMetadata,
|
||||||
optional: boolean): o.Expression {
|
optional: boolean): o.Expression {
|
||||||
var method = optional ? 'getOptional' : 'get';
|
var args = [createDiTokenExpression(token)];
|
||||||
return o.THIS_EXPR.prop('parentInjector').callMethod(method, [createDiTokenExpression(token)]);
|
if (optional) {
|
||||||
|
args.push(o.NULL_EXPR);
|
||||||
|
}
|
||||||
|
return o.THIS_EXPR.prop('parentInjector').callMethod('get', args);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getViewFactoryName(component: CompileDirectiveMetadata,
|
export function getViewFactoryName(component: CompileDirectiveMetadata,
|
||||||
|
@ -7,7 +7,7 @@ import {
|
|||||||
print,
|
print,
|
||||||
IS_DART
|
IS_DART
|
||||||
} from 'angular2/src/facade/lang';
|
} from 'angular2/src/facade/lang';
|
||||||
import {provide, Provider, Injector, OpaqueToken} from 'angular2/src/core/di';
|
import {provide, Provider, Injector, ReflectiveInjector, OpaqueToken} from 'angular2/src/core/di';
|
||||||
import {
|
import {
|
||||||
APP_COMPONENT_REF_PROMISE,
|
APP_COMPONENT_REF_PROMISE,
|
||||||
APP_COMPONENT,
|
APP_COMPONENT,
|
||||||
@ -48,7 +48,7 @@ function _componentProviders(appComponentType: Type): Array<Type | Provider | an
|
|||||||
() => { appRef._unloadComponent(ref); })
|
() => { appRef._unloadComponent(ref); })
|
||||||
.then((componentRef) => {
|
.then((componentRef) => {
|
||||||
ref = componentRef;
|
ref = componentRef;
|
||||||
var testability = injector.getOptional(Testability);
|
var testability = injector.get(Testability, null);
|
||||||
if (isPresent(testability)) {
|
if (isPresent(testability)) {
|
||||||
injector.get(TestabilityRegistry)
|
injector.get(TestabilityRegistry)
|
||||||
.registerApplication(componentRef.location.nativeElement, testability);
|
.registerApplication(componentRef.location.nativeElement, testability);
|
||||||
@ -115,7 +115,7 @@ export function disposePlatform(): void {
|
|||||||
|
|
||||||
function _createPlatform(providers?: Array<Type | Provider | any[]>): PlatformRef {
|
function _createPlatform(providers?: Array<Type | Provider | any[]>): PlatformRef {
|
||||||
_platformProviders = providers;
|
_platformProviders = providers;
|
||||||
let injector = Injector.resolveAndCreate(providers);
|
let injector = ReflectiveInjector.resolveAndCreate(providers);
|
||||||
_platform = new PlatformRef_(injector, () => {
|
_platform = new PlatformRef_(injector, () => {
|
||||||
_platform = null;
|
_platform = null;
|
||||||
_platformProviders = null;
|
_platformProviders = null;
|
||||||
@ -125,7 +125,7 @@ function _createPlatform(providers?: Array<Type | Provider | any[]>): PlatformRe
|
|||||||
}
|
}
|
||||||
|
|
||||||
function _runPlatformInitializers(injector: Injector): void {
|
function _runPlatformInitializers(injector: Injector): void {
|
||||||
let inits: Function[] = <Function[]>injector.getOptional(PLATFORM_INITIALIZER);
|
let inits: Function[] = <Function[]>injector.get(PLATFORM_INITIALIZER, null);
|
||||||
if (isPresent(inits)) inits.forEach(init => init());
|
if (isPresent(inits)) inits.forEach(init => init());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -201,11 +201,11 @@ export class PlatformRef_ extends PlatformRef {
|
|||||||
/** @internal */
|
/** @internal */
|
||||||
_disposeListeners: Function[] = [];
|
_disposeListeners: Function[] = [];
|
||||||
|
|
||||||
constructor(private _injector: Injector, private _dispose: () => void) { super(); }
|
constructor(private _injector: ReflectiveInjector, private _dispose: () => void) { super(); }
|
||||||
|
|
||||||
registerDisposeListener(dispose: () => void): void { this._disposeListeners.push(dispose); }
|
registerDisposeListener(dispose: () => void): void { this._disposeListeners.push(dispose); }
|
||||||
|
|
||||||
get injector(): Injector { return this._injector; }
|
get injector(): ReflectiveInjector { return this._injector; }
|
||||||
|
|
||||||
application(providers: Array<Type | Provider | any[]>): ApplicationRef {
|
application(providers: Array<Type | Provider | any[]>): ApplicationRef {
|
||||||
var app = this._initApp(createNgZone(), providers);
|
var app = this._initApp(createNgZone(), providers);
|
||||||
@ -239,7 +239,7 @@ export class PlatformRef_ extends PlatformRef {
|
|||||||
private _initApp(zone: NgZone,
|
private _initApp(zone: NgZone,
|
||||||
providers: Array<Type | Provider | any[]>): Promise<ApplicationRef>|
|
providers: Array<Type | Provider | any[]>): Promise<ApplicationRef>|
|
||||||
ApplicationRef {
|
ApplicationRef {
|
||||||
var injector: Injector;
|
var injector: ReflectiveInjector;
|
||||||
var app: ApplicationRef;
|
var app: ApplicationRef;
|
||||||
zone.run(() => {
|
zone.run(() => {
|
||||||
providers = ListWrapper.concat(providers, [
|
providers = ListWrapper.concat(providers, [
|
||||||
@ -283,7 +283,7 @@ export class PlatformRef_ extends PlatformRef {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function _runAppInitializers(injector: Injector): Promise<any> {
|
function _runAppInitializers(injector: Injector): Promise<any> {
|
||||||
let inits: Function[] = injector.getOptional(APP_INITIALIZER);
|
let inits: Function[] = injector.get(APP_INITIALIZER, null);
|
||||||
let promises: Promise<any>[] = [];
|
let promises: Promise<any>[] = [];
|
||||||
if (isPresent(inits)) {
|
if (isPresent(inits)) {
|
||||||
inits.forEach(init => {
|
inits.forEach(init => {
|
||||||
@ -390,7 +390,8 @@ export class ApplicationRef_ extends ApplicationRef {
|
|||||||
/** @internal */
|
/** @internal */
|
||||||
private _enforceNoNewChanges: boolean = false;
|
private _enforceNoNewChanges: boolean = false;
|
||||||
|
|
||||||
constructor(private _platform: PlatformRef_, private _zone: NgZone, private _injector: Injector) {
|
constructor(private _platform: PlatformRef_, private _zone: NgZone,
|
||||||
|
private _injector: ReflectiveInjector) {
|
||||||
super();
|
super();
|
||||||
if (isPresent(this._zone)) {
|
if (isPresent(this._zone)) {
|
||||||
ObservableWrapper.subscribe(this._zone.onMicrotaskEmpty,
|
ObservableWrapper.subscribe(this._zone.onMicrotaskEmpty,
|
||||||
|
@ -20,19 +20,23 @@ export * from './di/decorators';
|
|||||||
export {forwardRef, resolveForwardRef, ForwardRefFn} from './di/forward_ref';
|
export {forwardRef, resolveForwardRef, ForwardRefFn} from './di/forward_ref';
|
||||||
|
|
||||||
export {Injector} from './di/injector';
|
export {Injector} from './di/injector';
|
||||||
|
export {ReflectiveInjector} from './di/reflective_injector';
|
||||||
export {
|
export {
|
||||||
Binding,
|
Binding,
|
||||||
ProviderBuilder,
|
ProviderBuilder,
|
||||||
ResolvedBinding,
|
|
||||||
ResolvedFactory,
|
|
||||||
Dependency,
|
|
||||||
bind,
|
bind,
|
||||||
|
|
||||||
Provider,
|
Provider,
|
||||||
ResolvedProvider,
|
|
||||||
provide
|
provide
|
||||||
} from './di/provider';
|
} from './di/provider';
|
||||||
export {Key} from './di/key';
|
export {
|
||||||
|
ResolvedReflectiveBinding,
|
||||||
|
ResolvedReflectiveFactory,
|
||||||
|
ReflectiveDependency,
|
||||||
|
|
||||||
|
ResolvedReflectiveProvider
|
||||||
|
} from './di/reflective_provider';
|
||||||
|
export {ReflectiveKey} from './di/reflective_key';
|
||||||
export {
|
export {
|
||||||
NoProviderError,
|
NoProviderError,
|
||||||
AbstractProviderError,
|
AbstractProviderError,
|
||||||
@ -41,5 +45,5 @@ export {
|
|||||||
InvalidProviderError,
|
InvalidProviderError,
|
||||||
NoAnnotationError,
|
NoAnnotationError,
|
||||||
OutOfBoundsError
|
OutOfBoundsError
|
||||||
} from './di/exceptions';
|
} from './di/reflective_exceptions';
|
||||||
export {OpaqueToken} from './di/opaque_token';
|
export {OpaqueToken} from './di/opaque_token';
|
||||||
|
@ -1,442 +1,23 @@
|
|||||||
import {Map, MapWrapper, ListWrapper} from 'angular2/src/facade/collection';
|
import {CONST_EXPR} from 'angular2/src/facade/lang';
|
||||||
import {
|
import {unimplemented} from 'angular2/src/facade/exceptions';
|
||||||
ResolvedProvider,
|
|
||||||
Provider,
|
|
||||||
Dependency,
|
|
||||||
ProviderBuilder,
|
|
||||||
ResolvedFactory,
|
|
||||||
provide,
|
|
||||||
resolveProviders
|
|
||||||
} from './provider';
|
|
||||||
import {
|
|
||||||
AbstractProviderError,
|
|
||||||
NoProviderError,
|
|
||||||
CyclicDependencyError,
|
|
||||||
InstantiationError,
|
|
||||||
InvalidProviderError,
|
|
||||||
OutOfBoundsError
|
|
||||||
} from './exceptions';
|
|
||||||
import {Type, CONST_EXPR} from 'angular2/src/facade/lang';
|
|
||||||
import {BaseException, unimplemented} from 'angular2/src/facade/exceptions';
|
|
||||||
import {Key} from './key';
|
|
||||||
import {SelfMetadata, HostMetadata, SkipSelfMetadata} from './metadata';
|
|
||||||
|
|
||||||
var __unused: Type; // avoid unused import when Type union types are erased
|
const _THROW_IF_NOT_FOUND = CONST_EXPR(new Object());
|
||||||
|
export const THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
|
||||||
// Threshold for the dynamic version
|
|
||||||
const _MAX_CONSTRUCTION_COUNTER = 10;
|
|
||||||
|
|
||||||
export const UNDEFINED: Object = CONST_EXPR(new Object());
|
|
||||||
|
|
||||||
export interface ProtoInjectorStrategy {
|
|
||||||
getProviderAtIndex(index: number): ResolvedProvider;
|
|
||||||
createInjectorStrategy(inj: Injector_): InjectorStrategy;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class ProtoInjectorInlineStrategy implements ProtoInjectorStrategy {
|
|
||||||
provider0: ResolvedProvider = null;
|
|
||||||
provider1: ResolvedProvider = null;
|
|
||||||
provider2: ResolvedProvider = null;
|
|
||||||
provider3: ResolvedProvider = null;
|
|
||||||
provider4: ResolvedProvider = null;
|
|
||||||
provider5: ResolvedProvider = null;
|
|
||||||
provider6: ResolvedProvider = null;
|
|
||||||
provider7: ResolvedProvider = null;
|
|
||||||
provider8: ResolvedProvider = null;
|
|
||||||
provider9: ResolvedProvider = null;
|
|
||||||
|
|
||||||
keyId0: number = null;
|
|
||||||
keyId1: number = null;
|
|
||||||
keyId2: number = null;
|
|
||||||
keyId3: number = null;
|
|
||||||
keyId4: number = null;
|
|
||||||
keyId5: number = null;
|
|
||||||
keyId6: number = null;
|
|
||||||
keyId7: number = null;
|
|
||||||
keyId8: number = null;
|
|
||||||
keyId9: number = null;
|
|
||||||
|
|
||||||
constructor(protoEI: ProtoInjector, providers: ResolvedProvider[]) {
|
|
||||||
var length = providers.length;
|
|
||||||
|
|
||||||
if (length > 0) {
|
|
||||||
this.provider0 = providers[0];
|
|
||||||
this.keyId0 = providers[0].key.id;
|
|
||||||
}
|
|
||||||
if (length > 1) {
|
|
||||||
this.provider1 = providers[1];
|
|
||||||
this.keyId1 = providers[1].key.id;
|
|
||||||
}
|
|
||||||
if (length > 2) {
|
|
||||||
this.provider2 = providers[2];
|
|
||||||
this.keyId2 = providers[2].key.id;
|
|
||||||
}
|
|
||||||
if (length > 3) {
|
|
||||||
this.provider3 = providers[3];
|
|
||||||
this.keyId3 = providers[3].key.id;
|
|
||||||
}
|
|
||||||
if (length > 4) {
|
|
||||||
this.provider4 = providers[4];
|
|
||||||
this.keyId4 = providers[4].key.id;
|
|
||||||
}
|
|
||||||
if (length > 5) {
|
|
||||||
this.provider5 = providers[5];
|
|
||||||
this.keyId5 = providers[5].key.id;
|
|
||||||
}
|
|
||||||
if (length > 6) {
|
|
||||||
this.provider6 = providers[6];
|
|
||||||
this.keyId6 = providers[6].key.id;
|
|
||||||
}
|
|
||||||
if (length > 7) {
|
|
||||||
this.provider7 = providers[7];
|
|
||||||
this.keyId7 = providers[7].key.id;
|
|
||||||
}
|
|
||||||
if (length > 8) {
|
|
||||||
this.provider8 = providers[8];
|
|
||||||
this.keyId8 = providers[8].key.id;
|
|
||||||
}
|
|
||||||
if (length > 9) {
|
|
||||||
this.provider9 = providers[9];
|
|
||||||
this.keyId9 = providers[9].key.id;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
getProviderAtIndex(index: number): ResolvedProvider {
|
|
||||||
if (index == 0) return this.provider0;
|
|
||||||
if (index == 1) return this.provider1;
|
|
||||||
if (index == 2) return this.provider2;
|
|
||||||
if (index == 3) return this.provider3;
|
|
||||||
if (index == 4) return this.provider4;
|
|
||||||
if (index == 5) return this.provider5;
|
|
||||||
if (index == 6) return this.provider6;
|
|
||||||
if (index == 7) return this.provider7;
|
|
||||||
if (index == 8) return this.provider8;
|
|
||||||
if (index == 9) return this.provider9;
|
|
||||||
throw new OutOfBoundsError(index);
|
|
||||||
}
|
|
||||||
|
|
||||||
createInjectorStrategy(injector: Injector_): InjectorStrategy {
|
|
||||||
return new InjectorInlineStrategy(injector, this);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export class ProtoInjectorDynamicStrategy implements ProtoInjectorStrategy {
|
|
||||||
keyIds: number[];
|
|
||||||
|
|
||||||
constructor(protoInj: ProtoInjector, public providers: ResolvedProvider[]) {
|
|
||||||
var len = providers.length;
|
|
||||||
|
|
||||||
this.keyIds = ListWrapper.createFixedSize(len);
|
|
||||||
|
|
||||||
for (var i = 0; i < len; i++) {
|
|
||||||
this.keyIds[i] = providers[i].key.id;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
getProviderAtIndex(index: number): ResolvedProvider {
|
|
||||||
if (index < 0 || index >= this.providers.length) {
|
|
||||||
throw new OutOfBoundsError(index);
|
|
||||||
}
|
|
||||||
return this.providers[index];
|
|
||||||
}
|
|
||||||
|
|
||||||
createInjectorStrategy(ei: Injector_): InjectorStrategy {
|
|
||||||
return new InjectorDynamicStrategy(this, ei);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export class ProtoInjector {
|
|
||||||
static fromResolvedProviders(providers: ResolvedProvider[]): ProtoInjector {
|
|
||||||
return new ProtoInjector(providers);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @internal */
|
|
||||||
_strategy: ProtoInjectorStrategy;
|
|
||||||
numberOfProviders: number;
|
|
||||||
|
|
||||||
constructor(providers: ResolvedProvider[]) {
|
|
||||||
this.numberOfProviders = providers.length;
|
|
||||||
this._strategy = providers.length > _MAX_CONSTRUCTION_COUNTER ?
|
|
||||||
new ProtoInjectorDynamicStrategy(this, providers) :
|
|
||||||
new ProtoInjectorInlineStrategy(this, providers);
|
|
||||||
}
|
|
||||||
|
|
||||||
getProviderAtIndex(index: number): ResolvedProvider {
|
|
||||||
return this._strategy.getProviderAtIndex(index);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export interface InjectorStrategy {
|
|
||||||
getObjByKeyId(keyId: number): any;
|
|
||||||
getObjAtIndex(index: number): any;
|
|
||||||
getMaxNumberOfObjects(): number;
|
|
||||||
|
|
||||||
resetConstructionCounter(): void;
|
|
||||||
instantiateProvider(provider: ResolvedProvider): any;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class InjectorInlineStrategy implements InjectorStrategy {
|
|
||||||
obj0: any = UNDEFINED;
|
|
||||||
obj1: any = UNDEFINED;
|
|
||||||
obj2: any = UNDEFINED;
|
|
||||||
obj3: any = UNDEFINED;
|
|
||||||
obj4: any = UNDEFINED;
|
|
||||||
obj5: any = UNDEFINED;
|
|
||||||
obj6: any = UNDEFINED;
|
|
||||||
obj7: any = UNDEFINED;
|
|
||||||
obj8: any = UNDEFINED;
|
|
||||||
obj9: any = UNDEFINED;
|
|
||||||
|
|
||||||
constructor(public injector: Injector_, public protoStrategy: ProtoInjectorInlineStrategy) {}
|
|
||||||
|
|
||||||
resetConstructionCounter(): void { this.injector._constructionCounter = 0; }
|
|
||||||
|
|
||||||
instantiateProvider(provider: ResolvedProvider): any { return this.injector._new(provider); }
|
|
||||||
|
|
||||||
getObjByKeyId(keyId: number): any {
|
|
||||||
var p = this.protoStrategy;
|
|
||||||
var inj = this.injector;
|
|
||||||
|
|
||||||
if (p.keyId0 === keyId) {
|
|
||||||
if (this.obj0 === UNDEFINED) {
|
|
||||||
this.obj0 = inj._new(p.provider0);
|
|
||||||
}
|
|
||||||
return this.obj0;
|
|
||||||
}
|
|
||||||
if (p.keyId1 === keyId) {
|
|
||||||
if (this.obj1 === UNDEFINED) {
|
|
||||||
this.obj1 = inj._new(p.provider1);
|
|
||||||
}
|
|
||||||
return this.obj1;
|
|
||||||
}
|
|
||||||
if (p.keyId2 === keyId) {
|
|
||||||
if (this.obj2 === UNDEFINED) {
|
|
||||||
this.obj2 = inj._new(p.provider2);
|
|
||||||
}
|
|
||||||
return this.obj2;
|
|
||||||
}
|
|
||||||
if (p.keyId3 === keyId) {
|
|
||||||
if (this.obj3 === UNDEFINED) {
|
|
||||||
this.obj3 = inj._new(p.provider3);
|
|
||||||
}
|
|
||||||
return this.obj3;
|
|
||||||
}
|
|
||||||
if (p.keyId4 === keyId) {
|
|
||||||
if (this.obj4 === UNDEFINED) {
|
|
||||||
this.obj4 = inj._new(p.provider4);
|
|
||||||
}
|
|
||||||
return this.obj4;
|
|
||||||
}
|
|
||||||
if (p.keyId5 === keyId) {
|
|
||||||
if (this.obj5 === UNDEFINED) {
|
|
||||||
this.obj5 = inj._new(p.provider5);
|
|
||||||
}
|
|
||||||
return this.obj5;
|
|
||||||
}
|
|
||||||
if (p.keyId6 === keyId) {
|
|
||||||
if (this.obj6 === UNDEFINED) {
|
|
||||||
this.obj6 = inj._new(p.provider6);
|
|
||||||
}
|
|
||||||
return this.obj6;
|
|
||||||
}
|
|
||||||
if (p.keyId7 === keyId) {
|
|
||||||
if (this.obj7 === UNDEFINED) {
|
|
||||||
this.obj7 = inj._new(p.provider7);
|
|
||||||
}
|
|
||||||
return this.obj7;
|
|
||||||
}
|
|
||||||
if (p.keyId8 === keyId) {
|
|
||||||
if (this.obj8 === UNDEFINED) {
|
|
||||||
this.obj8 = inj._new(p.provider8);
|
|
||||||
}
|
|
||||||
return this.obj8;
|
|
||||||
}
|
|
||||||
if (p.keyId9 === keyId) {
|
|
||||||
if (this.obj9 === UNDEFINED) {
|
|
||||||
this.obj9 = inj._new(p.provider9);
|
|
||||||
}
|
|
||||||
return this.obj9;
|
|
||||||
}
|
|
||||||
|
|
||||||
return UNDEFINED;
|
|
||||||
}
|
|
||||||
|
|
||||||
getObjAtIndex(index: number): any {
|
|
||||||
if (index == 0) return this.obj0;
|
|
||||||
if (index == 1) return this.obj1;
|
|
||||||
if (index == 2) return this.obj2;
|
|
||||||
if (index == 3) return this.obj3;
|
|
||||||
if (index == 4) return this.obj4;
|
|
||||||
if (index == 5) return this.obj5;
|
|
||||||
if (index == 6) return this.obj6;
|
|
||||||
if (index == 7) return this.obj7;
|
|
||||||
if (index == 8) return this.obj8;
|
|
||||||
if (index == 9) return this.obj9;
|
|
||||||
throw new OutOfBoundsError(index);
|
|
||||||
}
|
|
||||||
|
|
||||||
getMaxNumberOfObjects(): number { return _MAX_CONSTRUCTION_COUNTER; }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
export class InjectorDynamicStrategy implements InjectorStrategy {
|
|
||||||
objs: any[];
|
|
||||||
|
|
||||||
constructor(public protoStrategy: ProtoInjectorDynamicStrategy, public injector: Injector_) {
|
|
||||||
this.objs = ListWrapper.createFixedSize(protoStrategy.providers.length);
|
|
||||||
ListWrapper.fill(this.objs, UNDEFINED);
|
|
||||||
}
|
|
||||||
|
|
||||||
resetConstructionCounter(): void { this.injector._constructionCounter = 0; }
|
|
||||||
|
|
||||||
instantiateProvider(provider: ResolvedProvider): any { return this.injector._new(provider); }
|
|
||||||
|
|
||||||
getObjByKeyId(keyId: number): any {
|
|
||||||
var p = this.protoStrategy;
|
|
||||||
|
|
||||||
for (var i = 0; i < p.keyIds.length; i++) {
|
|
||||||
if (p.keyIds[i] === keyId) {
|
|
||||||
if (this.objs[i] === UNDEFINED) {
|
|
||||||
this.objs[i] = this.injector._new(p.providers[i]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.objs[i];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return UNDEFINED;
|
|
||||||
}
|
|
||||||
|
|
||||||
getObjAtIndex(index: number): any {
|
|
||||||
if (index < 0 || index >= this.objs.length) {
|
|
||||||
throw new OutOfBoundsError(index);
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.objs[index];
|
|
||||||
}
|
|
||||||
|
|
||||||
getMaxNumberOfObjects(): number { return this.objs.length; }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Used to provide dependencies that cannot be easily expressed as providers.
|
|
||||||
*/
|
|
||||||
export interface DependencyProvider {
|
|
||||||
getDependency(injector: Injector, provider: ResolvedProvider, dependency: Dependency): any;
|
|
||||||
}
|
|
||||||
|
|
||||||
export abstract class Injector {
|
export abstract class Injector {
|
||||||
/**
|
static THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
|
||||||
* Turns an array of provider definitions into an array of resolved providers.
|
|
||||||
*
|
|
||||||
* A resolution is a process of flattening multiple nested arrays and converting individual
|
|
||||||
* providers into an array of {@link ResolvedProvider}s.
|
|
||||||
*
|
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/AiXTHi?p=preview))
|
|
||||||
*
|
|
||||||
* ```typescript
|
|
||||||
* @Injectable()
|
|
||||||
* class Engine {
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* @Injectable()
|
|
||||||
* class Car {
|
|
||||||
* constructor(public engine:Engine) {}
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* var providers = Injector.resolve([Car, [[Engine]]]);
|
|
||||||
*
|
|
||||||
* expect(providers.length).toEqual(2);
|
|
||||||
*
|
|
||||||
* expect(providers[0] instanceof ResolvedProvider).toBe(true);
|
|
||||||
* expect(providers[0].key.displayName).toBe("Car");
|
|
||||||
* expect(providers[0].dependencies.length).toEqual(1);
|
|
||||||
* expect(providers[0].factory).toBeDefined();
|
|
||||||
*
|
|
||||||
* expect(providers[1].key.displayName).toBe("Engine");
|
|
||||||
* });
|
|
||||||
* ```
|
|
||||||
*
|
|
||||||
* See {@link Injector#fromResolvedProviders} for more info.
|
|
||||||
*/
|
|
||||||
static resolve(providers: Array<Type | Provider | any[]>): ResolvedProvider[] {
|
|
||||||
return resolveProviders(providers);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolves an array of providers and creates an injector from those providers.
|
|
||||||
*
|
|
||||||
* The passed-in providers can be an array of `Type`, {@link Provider},
|
|
||||||
* or a recursive array of more providers.
|
|
||||||
*
|
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/ePOccA?p=preview))
|
|
||||||
*
|
|
||||||
* ```typescript
|
|
||||||
* @Injectable()
|
|
||||||
* class Engine {
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* @Injectable()
|
|
||||||
* class Car {
|
|
||||||
* constructor(public engine:Engine) {}
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* var injector = Injector.resolveAndCreate([Car, Engine]);
|
|
||||||
* expect(injector.get(Car) instanceof Car).toBe(true);
|
|
||||||
* ```
|
|
||||||
*
|
|
||||||
* This function is slower than the corresponding `fromResolvedProviders`
|
|
||||||
* because it needs to resolve the passed-in providers first.
|
|
||||||
* See {@link Injector#resolve} and {@link Injector#fromResolvedProviders}.
|
|
||||||
*/
|
|
||||||
static resolveAndCreate(providers: Array<Type | Provider | any[]>): Injector {
|
|
||||||
var resolvedProviders = Injector.resolve(providers);
|
|
||||||
return Injector.fromResolvedProviders(resolvedProviders);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates an injector from previously resolved providers.
|
|
||||||
*
|
|
||||||
* This API is the recommended way to construct injectors in performance-sensitive parts.
|
|
||||||
*
|
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/KrSMci?p=preview))
|
|
||||||
*
|
|
||||||
* ```typescript
|
|
||||||
* @Injectable()
|
|
||||||
* class Engine {
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* @Injectable()
|
|
||||||
* class Car {
|
|
||||||
* constructor(public engine:Engine) {}
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* var providers = Injector.resolve([Car, Engine]);
|
|
||||||
* var injector = Injector.fromResolvedProviders(providers);
|
|
||||||
* expect(injector.get(Car) instanceof Car).toBe(true);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
static fromResolvedProviders(providers: ResolvedProvider[]): Injector {
|
|
||||||
return new Injector_(ProtoInjector.fromResolvedProviders(providers));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @deprecated
|
|
||||||
*/
|
|
||||||
static fromResolvedBindings(providers: ResolvedProvider[]): Injector {
|
|
||||||
return Injector.fromResolvedProviders(providers);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves an instance from the injector based on the provided token.
|
* Retrieves an instance from the injector based on the provided token.
|
||||||
* Throws {@link NoProviderError} if not found.
|
* If not found:
|
||||||
|
* - Throws {@link NoProviderError} if no `notFoundValue` that is not equal to
|
||||||
|
* Injector.THROW_IF_NOT_FOUND is given
|
||||||
|
* - Returns the `notFoundValue` otherwise
|
||||||
*
|
*
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/HeXSHg?p=preview))
|
* ### Example ([live demo](http://plnkr.co/edit/HeXSHg?p=preview))
|
||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* var injector = Injector.resolveAndCreate([
|
* var injector = ReflectiveInjector.resolveAndCreate([
|
||||||
* provide("validToken", {useValue: "Value"})
|
* provide("validToken", {useValue: "Value"})
|
||||||
* ]);
|
* ]);
|
||||||
* expect(injector.get("validToken")).toEqual("Value");
|
* expect(injector.get("validToken")).toEqual("Value");
|
||||||
@ -446,484 +27,9 @@ export abstract class Injector {
|
|||||||
* `Injector` returns itself when given `Injector` as a token.
|
* `Injector` returns itself when given `Injector` as a token.
|
||||||
*
|
*
|
||||||
* ```typescript
|
* ```typescript
|
||||||
* var injector = Injector.resolveAndCreate([]);
|
* var injector = ReflectiveInjector.resolveAndCreate([]);
|
||||||
* expect(injector.get(Injector)).toBe(injector);
|
* expect(injector.get(Injector)).toBe(injector);
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
get(token: any): any { return unimplemented(); }
|
get(token: any, notFoundValue?: any): any { return unimplemented(); }
|
||||||
|
|
||||||
/**
|
|
||||||
* Retrieves an instance from the injector based on the provided token.
|
|
||||||
* Returns null if not found.
|
|
||||||
*
|
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/tpEbEy?p=preview))
|
|
||||||
*
|
|
||||||
* ```typescript
|
|
||||||
* var injector = Injector.resolveAndCreate([
|
|
||||||
* provide("validToken", {useValue: "Value"})
|
|
||||||
* ]);
|
|
||||||
* expect(injector.getOptional("validToken")).toEqual("Value");
|
|
||||||
* expect(injector.getOptional("invalidToken")).toBe(null);
|
|
||||||
* ```
|
|
||||||
*
|
|
||||||
* `Injector` returns itself when given `Injector` as a token.
|
|
||||||
*
|
|
||||||
* ```typescript
|
|
||||||
* var injector = Injector.resolveAndCreate([]);
|
|
||||||
* expect(injector.getOptional(Injector)).toBe(injector);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
getOptional(token: any): any { return unimplemented(); }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parent of this injector.
|
|
||||||
*
|
|
||||||
* <!-- TODO: Add a link to the section of the user guide talking about hierarchical injection.
|
|
||||||
* -->
|
|
||||||
*
|
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/eosMGo?p=preview))
|
|
||||||
*
|
|
||||||
* ```typescript
|
|
||||||
* var parent = Injector.resolveAndCreate([]);
|
|
||||||
* var child = parent.resolveAndCreateChild([]);
|
|
||||||
* expect(child.parent).toBe(parent);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
get parent(): Injector { return unimplemented(); }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @internal
|
|
||||||
*/
|
|
||||||
debugContext(): any { return null; }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolves an array of providers and creates a child injector from those providers.
|
|
||||||
*
|
|
||||||
* <!-- TODO: Add a link to the section of the user guide talking about hierarchical injection.
|
|
||||||
* -->
|
|
||||||
*
|
|
||||||
* The passed-in providers can be an array of `Type`, {@link Provider},
|
|
||||||
* or a recursive array of more providers.
|
|
||||||
*
|
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/opB3T4?p=preview))
|
|
||||||
*
|
|
||||||
* ```typescript
|
|
||||||
* class ParentProvider {}
|
|
||||||
* class ChildProvider {}
|
|
||||||
*
|
|
||||||
* var parent = Injector.resolveAndCreate([ParentProvider]);
|
|
||||||
* var child = parent.resolveAndCreateChild([ChildProvider]);
|
|
||||||
*
|
|
||||||
* expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true);
|
|
||||||
* expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true);
|
|
||||||
* expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider));
|
|
||||||
* ```
|
|
||||||
*
|
|
||||||
* This function is slower than the corresponding `createChildFromResolved`
|
|
||||||
* because it needs to resolve the passed-in providers first.
|
|
||||||
* See {@link Injector#resolve} and {@link Injector#createChildFromResolved}.
|
|
||||||
*/
|
|
||||||
resolveAndCreateChild(providers: Array<Type | Provider | any[]>): Injector {
|
|
||||||
return unimplemented();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a child injector from previously resolved providers.
|
|
||||||
*
|
|
||||||
* <!-- TODO: Add a link to the section of the user guide talking about hierarchical injection.
|
|
||||||
* -->
|
|
||||||
*
|
|
||||||
* This API is the recommended way to construct injectors in performance-sensitive parts.
|
|
||||||
*
|
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/VhyfjN?p=preview))
|
|
||||||
*
|
|
||||||
* ```typescript
|
|
||||||
* class ParentProvider {}
|
|
||||||
* class ChildProvider {}
|
|
||||||
*
|
|
||||||
* var parentProviders = Injector.resolve([ParentProvider]);
|
|
||||||
* var childProviders = Injector.resolve([ChildProvider]);
|
|
||||||
*
|
|
||||||
* var parent = Injector.fromResolvedProviders(parentProviders);
|
|
||||||
* var child = parent.createChildFromResolved(childProviders);
|
|
||||||
*
|
|
||||||
* expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true);
|
|
||||||
* expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true);
|
|
||||||
* expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
createChildFromResolved(providers: ResolvedProvider[]): Injector { return unimplemented(); }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolves a provider and instantiates an object in the context of the injector.
|
|
||||||
*
|
|
||||||
* The created object does not get cached by the injector.
|
|
||||||
*
|
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/yvVXoB?p=preview))
|
|
||||||
*
|
|
||||||
* ```typescript
|
|
||||||
* @Injectable()
|
|
||||||
* class Engine {
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* @Injectable()
|
|
||||||
* class Car {
|
|
||||||
* constructor(public engine:Engine) {}
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* var injector = Injector.resolveAndCreate([Engine]);
|
|
||||||
*
|
|
||||||
* var car = injector.resolveAndInstantiate(Car);
|
|
||||||
* expect(car.engine).toBe(injector.get(Engine));
|
|
||||||
* expect(car).not.toBe(injector.resolveAndInstantiate(Car));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
resolveAndInstantiate(provider: Type | Provider): any { return unimplemented(); }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Instantiates an object using a resolved provider in the context of the injector.
|
|
||||||
*
|
|
||||||
* The created object does not get cached by the injector.
|
|
||||||
*
|
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/ptCImQ?p=preview))
|
|
||||||
*
|
|
||||||
* ```typescript
|
|
||||||
* @Injectable()
|
|
||||||
* class Engine {
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* @Injectable()
|
|
||||||
* class Car {
|
|
||||||
* constructor(public engine:Engine) {}
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* var injector = Injector.resolveAndCreate([Engine]);
|
|
||||||
* var carProvider = Injector.resolve([Car])[0];
|
|
||||||
* var car = injector.instantiateResolved(carProvider);
|
|
||||||
* expect(car.engine).toBe(injector.get(Engine));
|
|
||||||
* expect(car).not.toBe(injector.instantiateResolved(carProvider));
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
instantiateResolved(provider: ResolvedProvider): any { return unimplemented(); }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A dependency injection container used for instantiating objects and resolving dependencies.
|
|
||||||
*
|
|
||||||
* An `Injector` is a replacement for a `new` operator, which can automatically resolve the
|
|
||||||
* constructor dependencies.
|
|
||||||
*
|
|
||||||
* In typical use, application code asks for the dependencies in the constructor and they are
|
|
||||||
* resolved by the `Injector`.
|
|
||||||
*
|
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/jzjec0?p=preview))
|
|
||||||
*
|
|
||||||
* The following example creates an `Injector` configured to create `Engine` and `Car`.
|
|
||||||
*
|
|
||||||
* ```typescript
|
|
||||||
* @Injectable()
|
|
||||||
* class Engine {
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* @Injectable()
|
|
||||||
* class Car {
|
|
||||||
* constructor(public engine:Engine) {}
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* var injector = Injector.resolveAndCreate([Car, Engine]);
|
|
||||||
* var car = injector.get(Car);
|
|
||||||
* expect(car instanceof Car).toBe(true);
|
|
||||||
* expect(car.engine instanceof Engine).toBe(true);
|
|
||||||
* ```
|
|
||||||
*
|
|
||||||
* Notice, we don't use the `new` operator because we explicitly want to have the `Injector`
|
|
||||||
* resolve all of the object's dependencies automatically.
|
|
||||||
*/
|
|
||||||
export class Injector_ implements Injector {
|
|
||||||
/** @internal */
|
|
||||||
_strategy: InjectorStrategy;
|
|
||||||
/** @internal */
|
|
||||||
_constructionCounter: number = 0;
|
|
||||||
/** @internal */
|
|
||||||
public _proto: any /* ProtoInjector */;
|
|
||||||
/** @internal */
|
|
||||||
public _parent: Injector;
|
|
||||||
/**
|
|
||||||
* Private
|
|
||||||
*/
|
|
||||||
constructor(_proto: any /* ProtoInjector */, _parent: Injector = null,
|
|
||||||
private _debugContext: Function = null) {
|
|
||||||
this._proto = _proto;
|
|
||||||
this._parent = _parent;
|
|
||||||
this._strategy = _proto._strategy.createInjectorStrategy(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @internal
|
|
||||||
*/
|
|
||||||
debugContext(): any { return this._debugContext(); }
|
|
||||||
|
|
||||||
get(token: any): any { return this._getByKey(Key.get(token), null, null, false); }
|
|
||||||
|
|
||||||
getOptional(token: any): any { return this._getByKey(Key.get(token), null, null, true); }
|
|
||||||
|
|
||||||
getAt(index: number): any { return this._strategy.getObjAtIndex(index); }
|
|
||||||
|
|
||||||
get parent(): Injector { return this._parent; }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @internal
|
|
||||||
* Internal. Do not use.
|
|
||||||
* We return `any` not to export the InjectorStrategy type.
|
|
||||||
*/
|
|
||||||
get internalStrategy(): any { return this._strategy; }
|
|
||||||
|
|
||||||
resolveAndCreateChild(providers: Array<Type | Provider | any[]>): Injector {
|
|
||||||
var resolvedProviders = Injector.resolve(providers);
|
|
||||||
return this.createChildFromResolved(resolvedProviders);
|
|
||||||
}
|
|
||||||
|
|
||||||
createChildFromResolved(providers: ResolvedProvider[]): Injector {
|
|
||||||
var proto = new ProtoInjector(providers);
|
|
||||||
var inj = new Injector_(proto);
|
|
||||||
inj._parent = this;
|
|
||||||
return inj;
|
|
||||||
}
|
|
||||||
|
|
||||||
resolveAndInstantiate(provider: Type | Provider): any {
|
|
||||||
return this.instantiateResolved(Injector.resolve([provider])[0]);
|
|
||||||
}
|
|
||||||
|
|
||||||
instantiateResolved(provider: ResolvedProvider): any {
|
|
||||||
return this._instantiateProvider(provider);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @internal */
|
|
||||||
_new(provider: ResolvedProvider): any {
|
|
||||||
if (this._constructionCounter++ > this._strategy.getMaxNumberOfObjects()) {
|
|
||||||
throw new CyclicDependencyError(this, provider.key);
|
|
||||||
}
|
|
||||||
return this._instantiateProvider(provider);
|
|
||||||
}
|
|
||||||
|
|
||||||
private _instantiateProvider(provider: ResolvedProvider): any {
|
|
||||||
if (provider.multiProvider) {
|
|
||||||
var res = ListWrapper.createFixedSize(provider.resolvedFactories.length);
|
|
||||||
for (var i = 0; i < provider.resolvedFactories.length; ++i) {
|
|
||||||
res[i] = this._instantiate(provider, provider.resolvedFactories[i]);
|
|
||||||
}
|
|
||||||
return res;
|
|
||||||
} else {
|
|
||||||
return this._instantiate(provider, provider.resolvedFactories[0]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private _instantiate(provider: ResolvedProvider, resolvedFactory: ResolvedFactory): any {
|
|
||||||
var factory = resolvedFactory.factory;
|
|
||||||
var deps = resolvedFactory.dependencies;
|
|
||||||
var length = deps.length;
|
|
||||||
|
|
||||||
var d0: any;
|
|
||||||
var d1: any;
|
|
||||||
var d2: any;
|
|
||||||
var d3: any;
|
|
||||||
var d4: any;
|
|
||||||
var d5: any;
|
|
||||||
var d6: any;
|
|
||||||
var d7: any;
|
|
||||||
var d8: any;
|
|
||||||
var d9: any;
|
|
||||||
var d10: any;
|
|
||||||
var d11: any;
|
|
||||||
var d12: any;
|
|
||||||
var d13: any;
|
|
||||||
var d14: any;
|
|
||||||
var d15: any;
|
|
||||||
var d16: any;
|
|
||||||
var d17: any;
|
|
||||||
var d18: any;
|
|
||||||
var d19: any;
|
|
||||||
try {
|
|
||||||
d0 = length > 0 ? this._getByDependency(provider, deps[0]) : null;
|
|
||||||
d1 = length > 1 ? this._getByDependency(provider, deps[1]) : null;
|
|
||||||
d2 = length > 2 ? this._getByDependency(provider, deps[2]) : null;
|
|
||||||
d3 = length > 3 ? this._getByDependency(provider, deps[3]) : null;
|
|
||||||
d4 = length > 4 ? this._getByDependency(provider, deps[4]) : null;
|
|
||||||
d5 = length > 5 ? this._getByDependency(provider, deps[5]) : null;
|
|
||||||
d6 = length > 6 ? this._getByDependency(provider, deps[6]) : null;
|
|
||||||
d7 = length > 7 ? this._getByDependency(provider, deps[7]) : null;
|
|
||||||
d8 = length > 8 ? this._getByDependency(provider, deps[8]) : null;
|
|
||||||
d9 = length > 9 ? this._getByDependency(provider, deps[9]) : null;
|
|
||||||
d10 = length > 10 ? this._getByDependency(provider, deps[10]) : null;
|
|
||||||
d11 = length > 11 ? this._getByDependency(provider, deps[11]) : null;
|
|
||||||
d12 = length > 12 ? this._getByDependency(provider, deps[12]) : null;
|
|
||||||
d13 = length > 13 ? this._getByDependency(provider, deps[13]) : null;
|
|
||||||
d14 = length > 14 ? this._getByDependency(provider, deps[14]) : null;
|
|
||||||
d15 = length > 15 ? this._getByDependency(provider, deps[15]) : null;
|
|
||||||
d16 = length > 16 ? this._getByDependency(provider, deps[16]) : null;
|
|
||||||
d17 = length > 17 ? this._getByDependency(provider, deps[17]) : null;
|
|
||||||
d18 = length > 18 ? this._getByDependency(provider, deps[18]) : null;
|
|
||||||
d19 = length > 19 ? this._getByDependency(provider, deps[19]) : null;
|
|
||||||
} catch (e) {
|
|
||||||
if (e instanceof AbstractProviderError || e instanceof InstantiationError) {
|
|
||||||
e.addKey(this, provider.key);
|
|
||||||
}
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
|
|
||||||
var obj;
|
|
||||||
try {
|
|
||||||
switch (length) {
|
|
||||||
case 0:
|
|
||||||
obj = factory();
|
|
||||||
break;
|
|
||||||
case 1:
|
|
||||||
obj = factory(d0);
|
|
||||||
break;
|
|
||||||
case 2:
|
|
||||||
obj = factory(d0, d1);
|
|
||||||
break;
|
|
||||||
case 3:
|
|
||||||
obj = factory(d0, d1, d2);
|
|
||||||
break;
|
|
||||||
case 4:
|
|
||||||
obj = factory(d0, d1, d2, d3);
|
|
||||||
break;
|
|
||||||
case 5:
|
|
||||||
obj = factory(d0, d1, d2, d3, d4);
|
|
||||||
break;
|
|
||||||
case 6:
|
|
||||||
obj = factory(d0, d1, d2, d3, d4, d5);
|
|
||||||
break;
|
|
||||||
case 7:
|
|
||||||
obj = factory(d0, d1, d2, d3, d4, d5, d6);
|
|
||||||
break;
|
|
||||||
case 8:
|
|
||||||
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7);
|
|
||||||
break;
|
|
||||||
case 9:
|
|
||||||
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8);
|
|
||||||
break;
|
|
||||||
case 10:
|
|
||||||
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9);
|
|
||||||
break;
|
|
||||||
case 11:
|
|
||||||
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10);
|
|
||||||
break;
|
|
||||||
case 12:
|
|
||||||
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11);
|
|
||||||
break;
|
|
||||||
case 13:
|
|
||||||
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12);
|
|
||||||
break;
|
|
||||||
case 14:
|
|
||||||
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13);
|
|
||||||
break;
|
|
||||||
case 15:
|
|
||||||
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14);
|
|
||||||
break;
|
|
||||||
case 16:
|
|
||||||
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15);
|
|
||||||
break;
|
|
||||||
case 17:
|
|
||||||
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16);
|
|
||||||
break;
|
|
||||||
case 18:
|
|
||||||
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16,
|
|
||||||
d17);
|
|
||||||
break;
|
|
||||||
case 19:
|
|
||||||
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16,
|
|
||||||
d17, d18);
|
|
||||||
break;
|
|
||||||
case 20:
|
|
||||||
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16,
|
|
||||||
d17, d18, d19);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
throw new BaseException(
|
|
||||||
`Cannot instantiate '${provider.key.displayName}' because it has more than 20 dependencies`);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
throw new InstantiationError(this, e, e.stack, provider.key);
|
|
||||||
}
|
|
||||||
return obj;
|
|
||||||
}
|
|
||||||
|
|
||||||
private _getByDependency(provider: ResolvedProvider, dep: Dependency): any {
|
|
||||||
return this._getByKey(dep.key, dep.lowerBoundVisibility, dep.upperBoundVisibility,
|
|
||||||
dep.optional);
|
|
||||||
}
|
|
||||||
|
|
||||||
private _getByKey(key: Key, lowerBoundVisibility: Object, upperBoundVisibility: Object,
|
|
||||||
optional: boolean): any {
|
|
||||||
if (key === INJECTOR_KEY) {
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (upperBoundVisibility instanceof SelfMetadata) {
|
|
||||||
return this._getByKeySelf(key, optional);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
return this._getByKeyDefault(key, optional, lowerBoundVisibility);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @internal */
|
|
||||||
_throwOrNull(key: Key, optional: boolean): any {
|
|
||||||
if (optional) {
|
|
||||||
return null;
|
|
||||||
} else {
|
|
||||||
throw new NoProviderError(this, key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @internal */
|
|
||||||
_getByKeySelf(key: Key, optional: boolean): any {
|
|
||||||
var obj = this._strategy.getObjByKeyId(key.id);
|
|
||||||
return (obj !== UNDEFINED) ? obj : this._throwOrNull(key, optional);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @internal */
|
|
||||||
_getByKeyDefault(key: Key, optional: boolean, lowerBoundVisibility: Object): any {
|
|
||||||
var inj: Injector;
|
|
||||||
|
|
||||||
if (lowerBoundVisibility instanceof SkipSelfMetadata) {
|
|
||||||
inj = this._parent;
|
|
||||||
} else {
|
|
||||||
inj = this;
|
|
||||||
}
|
|
||||||
|
|
||||||
while (inj instanceof Injector_) {
|
|
||||||
var inj_ = <Injector_>inj;
|
|
||||||
var obj = inj_._strategy.getObjByKeyId(key.id);
|
|
||||||
if (obj !== UNDEFINED) return obj;
|
|
||||||
inj = inj_._parent;
|
|
||||||
}
|
|
||||||
if (inj !== null) {
|
|
||||||
if (optional) {
|
|
||||||
return inj.getOptional(key.token);
|
|
||||||
} else {
|
|
||||||
return inj.get(key.token);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return this._throwOrNull(key, optional);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
get displayName(): string {
|
|
||||||
return `Injector(providers: [${_mapProviders(this, (b: ResolvedProvider) => ` "${b.key.displayName}" `).join(", ")}])`;
|
|
||||||
}
|
|
||||||
|
|
||||||
toString(): string { return this.displayName; }
|
|
||||||
}
|
|
||||||
|
|
||||||
var INJECTOR_KEY = Key.get(Injector);
|
|
||||||
|
|
||||||
function _mapProviders(injector: Injector_, fn: Function): any[] {
|
|
||||||
var res = [];
|
|
||||||
for (var i = 0; i < injector._proto.numberOfProviders; ++i) {
|
|
||||||
res.push(fn(injector._proto.getProviderAtIndex(i)));
|
|
||||||
}
|
|
||||||
return res;
|
|
||||||
}
|
}
|
||||||
|
@ -1,47 +1,13 @@
|
|||||||
import {
|
import {
|
||||||
|
normalizeBool,
|
||||||
Type,
|
Type,
|
||||||
isBlank,
|
|
||||||
isPresent,
|
|
||||||
CONST,
|
CONST,
|
||||||
CONST_EXPR,
|
|
||||||
stringify,
|
|
||||||
isArray,
|
|
||||||
isType,
|
isType,
|
||||||
|
isBlank,
|
||||||
isFunction,
|
isFunction,
|
||||||
normalizeBool
|
stringify
|
||||||
} from 'angular2/src/facade/lang';
|
} from 'angular2/src/facade/lang';
|
||||||
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
|
import {BaseException} from 'angular2/src/facade/exceptions';
|
||||||
import {MapWrapper, ListWrapper} from 'angular2/src/facade/collection';
|
|
||||||
import {reflector} from 'angular2/src/core/reflection/reflection';
|
|
||||||
import {Key} from './key';
|
|
||||||
import {
|
|
||||||
InjectMetadata,
|
|
||||||
InjectableMetadata,
|
|
||||||
OptionalMetadata,
|
|
||||||
SelfMetadata,
|
|
||||||
HostMetadata,
|
|
||||||
SkipSelfMetadata,
|
|
||||||
DependencyMetadata
|
|
||||||
} from './metadata';
|
|
||||||
import {
|
|
||||||
NoAnnotationError,
|
|
||||||
MixingMultiProvidersWithRegularProvidersError,
|
|
||||||
InvalidProviderError
|
|
||||||
} from './exceptions';
|
|
||||||
import {resolveForwardRef} from './forward_ref';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* `Dependency` is used by the framework to extend DI.
|
|
||||||
* This is internal to Angular and should not be used directly.
|
|
||||||
*/
|
|
||||||
export class Dependency {
|
|
||||||
constructor(public key: Key, public optional: boolean, public lowerBoundVisibility: any,
|
|
||||||
public upperBoundVisibility: any, public properties: any[]) {}
|
|
||||||
|
|
||||||
static fromKey(key: Key): Dependency { return new Dependency(key, false, null, null, []); }
|
|
||||||
}
|
|
||||||
|
|
||||||
const _EMPTY_LIST = CONST_EXPR([]);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Describes how the {@link Injector} should instantiate a given token.
|
* Describes how the {@link Injector} should instantiate a given token.
|
||||||
@ -283,69 +249,6 @@ export class Binding extends Provider {
|
|||||||
get toValue() { return this.useValue; }
|
get toValue() { return this.useValue; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* An internal resolved representation of a {@link Provider} used by the {@link Injector}.
|
|
||||||
*
|
|
||||||
* It is usually created automatically by `Injector.resolveAndCreate`.
|
|
||||||
*
|
|
||||||
* It can be created manually, as follows:
|
|
||||||
*
|
|
||||||
* ### Example ([live demo](http://plnkr.co/edit/RfEnhh8kUEI0G3qsnIeT?p%3Dpreview&p=preview))
|
|
||||||
*
|
|
||||||
* ```typescript
|
|
||||||
* var resolvedProviders = Injector.resolve([new Provider('message', {useValue: 'Hello'})]);
|
|
||||||
* var injector = Injector.fromResolvedProviders(resolvedProviders);
|
|
||||||
*
|
|
||||||
* expect(injector.get('message')).toEqual('Hello');
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export interface ResolvedProvider {
|
|
||||||
/**
|
|
||||||
* A key, usually a `Type`.
|
|
||||||
*/
|
|
||||||
key: Key;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Factory function which can return an instance of an object represented by a key.
|
|
||||||
*/
|
|
||||||
resolvedFactories: ResolvedFactory[];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Indicates if the provider is a multi-provider or a regular provider.
|
|
||||||
*/
|
|
||||||
multiProvider: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* See {@link ResolvedProvider} instead.
|
|
||||||
*
|
|
||||||
* @deprecated
|
|
||||||
*/
|
|
||||||
export interface ResolvedBinding extends ResolvedProvider {}
|
|
||||||
|
|
||||||
export class ResolvedProvider_ implements ResolvedBinding {
|
|
||||||
constructor(public key: Key, public resolvedFactories: ResolvedFactory[],
|
|
||||||
public multiProvider: boolean) {}
|
|
||||||
|
|
||||||
get resolvedFactory(): ResolvedFactory { return this.resolvedFactories[0]; }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* An internal resolved representation of a factory function created by resolving {@link Provider}.
|
|
||||||
*/
|
|
||||||
export class ResolvedFactory {
|
|
||||||
constructor(
|
|
||||||
/**
|
|
||||||
* Factory function which can return an instance of an object represented by a key.
|
|
||||||
*/
|
|
||||||
public factory: Function,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Arguments (dependencies) to the `factory` function.
|
|
||||||
*/
|
|
||||||
public dependencies: Dependency[]) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a {@link Provider}.
|
* Creates a {@link Provider}.
|
||||||
*
|
*
|
||||||
@ -362,31 +265,6 @@ export function bind(token): ProviderBuilder {
|
|||||||
return new ProviderBuilder(token);
|
return new ProviderBuilder(token);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a {@link Provider}.
|
|
||||||
*
|
|
||||||
* See {@link Provider} for more details.
|
|
||||||
*
|
|
||||||
* <!-- TODO: improve the docs -->
|
|
||||||
*/
|
|
||||||
export function provide(token, {useClass, useValue, useExisting, useFactory, deps, multi}: {
|
|
||||||
useClass?: Type,
|
|
||||||
useValue?: any,
|
|
||||||
useExisting?: any,
|
|
||||||
useFactory?: Function,
|
|
||||||
deps?: Object[],
|
|
||||||
multi?: boolean
|
|
||||||
}): Provider {
|
|
||||||
return new Provider(token, {
|
|
||||||
useClass: useClass,
|
|
||||||
useValue: useValue,
|
|
||||||
useExisting: useExisting,
|
|
||||||
useFactory: useFactory,
|
|
||||||
deps: deps,
|
|
||||||
multi: multi
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper class for the {@link bind} function.
|
* Helper class for the {@link bind} function.
|
||||||
*/
|
*/
|
||||||
@ -509,180 +387,26 @@ export class ProviderBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve a single provider.
|
* Creates a {@link Provider}.
|
||||||
*/
|
|
||||||
export function resolveFactory(provider: Provider): ResolvedFactory {
|
|
||||||
var factoryFn: Function;
|
|
||||||
var resolvedDeps;
|
|
||||||
if (isPresent(provider.useClass)) {
|
|
||||||
var useClass = resolveForwardRef(provider.useClass);
|
|
||||||
factoryFn = reflector.factory(useClass);
|
|
||||||
resolvedDeps = _dependenciesFor(useClass);
|
|
||||||
} else if (isPresent(provider.useExisting)) {
|
|
||||||
factoryFn = (aliasInstance) => aliasInstance;
|
|
||||||
resolvedDeps = [Dependency.fromKey(Key.get(provider.useExisting))];
|
|
||||||
} else if (isPresent(provider.useFactory)) {
|
|
||||||
factoryFn = provider.useFactory;
|
|
||||||
resolvedDeps = constructDependencies(provider.useFactory, provider.dependencies);
|
|
||||||
} else {
|
|
||||||
factoryFn = () => provider.useValue;
|
|
||||||
resolvedDeps = _EMPTY_LIST;
|
|
||||||
}
|
|
||||||
return new ResolvedFactory(factoryFn, resolvedDeps);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Converts the {@link Provider} into {@link ResolvedProvider}.
|
|
||||||
*
|
*
|
||||||
* {@link Injector} internally only uses {@link ResolvedProvider}, {@link Provider} contains
|
* See {@link Provider} for more details.
|
||||||
* convenience provider syntax.
|
*
|
||||||
|
* <!-- TODO: improve the docs -->
|
||||||
*/
|
*/
|
||||||
export function resolveProvider(provider: Provider): ResolvedProvider {
|
export function provide(token, {useClass, useValue, useExisting, useFactory, deps, multi}: {
|
||||||
return new ResolvedProvider_(Key.get(provider.token), [resolveFactory(provider)], provider.multi);
|
useClass?: Type,
|
||||||
}
|
useValue?: any,
|
||||||
|
useExisting?: any,
|
||||||
/**
|
useFactory?: Function,
|
||||||
* Resolve a list of Providers.
|
deps?: Object[],
|
||||||
*/
|
multi?: boolean
|
||||||
export function resolveProviders(providers: Array<Type | Provider | any[]>): ResolvedProvider[] {
|
}): Provider {
|
||||||
var normalized = _normalizeProviders(providers, []);
|
return new Provider(token, {
|
||||||
var resolved = normalized.map(resolveProvider);
|
useClass: useClass,
|
||||||
return MapWrapper.values(mergeResolvedProviders(resolved, new Map<number, ResolvedProvider>()));
|
useValue: useValue,
|
||||||
}
|
useExisting: useExisting,
|
||||||
|
useFactory: useFactory,
|
||||||
/**
|
deps: deps,
|
||||||
* Merges a list of ResolvedProviders into a list where
|
multi: multi
|
||||||
* each key is contained exactly once and multi providers
|
|
||||||
* have been merged.
|
|
||||||
*/
|
|
||||||
export function mergeResolvedProviders(
|
|
||||||
providers: ResolvedProvider[],
|
|
||||||
normalizedProvidersMap: Map<number, ResolvedProvider>): Map<number, ResolvedProvider> {
|
|
||||||
for (var i = 0; i < providers.length; i++) {
|
|
||||||
var provider = providers[i];
|
|
||||||
var existing = normalizedProvidersMap.get(provider.key.id);
|
|
||||||
if (isPresent(existing)) {
|
|
||||||
if (provider.multiProvider !== existing.multiProvider) {
|
|
||||||
throw new MixingMultiProvidersWithRegularProvidersError(existing, provider);
|
|
||||||
}
|
|
||||||
if (provider.multiProvider) {
|
|
||||||
for (var j = 0; j < provider.resolvedFactories.length; j++) {
|
|
||||||
existing.resolvedFactories.push(provider.resolvedFactories[j]);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
normalizedProvidersMap.set(provider.key.id, provider);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
var resolvedProvider;
|
|
||||||
if (provider.multiProvider) {
|
|
||||||
resolvedProvider = new ResolvedProvider_(
|
|
||||||
provider.key, ListWrapper.clone(provider.resolvedFactories), provider.multiProvider);
|
|
||||||
} else {
|
|
||||||
resolvedProvider = provider;
|
|
||||||
}
|
|
||||||
normalizedProvidersMap.set(provider.key.id, resolvedProvider);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return normalizedProvidersMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _normalizeProviders(providers: Array<Type | Provider | ProviderBuilder | any[]>,
|
|
||||||
res: Provider[]): Provider[] {
|
|
||||||
providers.forEach(b => {
|
|
||||||
if (b instanceof Type) {
|
|
||||||
res.push(provide(b, {useClass: b}));
|
|
||||||
|
|
||||||
} else if (b instanceof Provider) {
|
|
||||||
res.push(b);
|
|
||||||
|
|
||||||
} else if (b instanceof Array) {
|
|
||||||
_normalizeProviders(b, res);
|
|
||||||
|
|
||||||
} else if (b instanceof ProviderBuilder) {
|
|
||||||
throw new InvalidProviderError(b.token);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
throw new InvalidProviderError(b);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function constructDependencies(typeOrFunc: any, dependencies: any[]): Dependency[] {
|
|
||||||
if (isBlank(dependencies)) {
|
|
||||||
return _dependenciesFor(typeOrFunc);
|
|
||||||
} else {
|
|
||||||
var params: any[][] = dependencies.map(t => [t]);
|
|
||||||
return dependencies.map(t => _extractToken(typeOrFunc, t, params));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function _dependenciesFor(typeOrFunc: any): Dependency[] {
|
|
||||||
var params = reflector.parameters(typeOrFunc);
|
|
||||||
if (isBlank(params)) return [];
|
|
||||||
if (params.some(isBlank)) {
|
|
||||||
throw new NoAnnotationError(typeOrFunc, params);
|
|
||||||
}
|
|
||||||
return params.map((p: any[]) => _extractToken(typeOrFunc, p, params));
|
|
||||||
}
|
|
||||||
|
|
||||||
function _extractToken(typeOrFunc, metadata /*any[] | any*/, params: any[][]): Dependency {
|
|
||||||
var depProps = [];
|
|
||||||
var token = null;
|
|
||||||
var optional = false;
|
|
||||||
|
|
||||||
if (!isArray(metadata)) {
|
|
||||||
if (metadata instanceof InjectMetadata) {
|
|
||||||
return _createDependency(metadata.token, optional, null, null, depProps);
|
|
||||||
} else {
|
|
||||||
return _createDependency(metadata, optional, null, null, depProps);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var lowerBoundVisibility = null;
|
|
||||||
var upperBoundVisibility = null;
|
|
||||||
|
|
||||||
for (var i = 0; i < metadata.length; ++i) {
|
|
||||||
var paramMetadata = metadata[i];
|
|
||||||
|
|
||||||
if (paramMetadata instanceof Type) {
|
|
||||||
token = paramMetadata;
|
|
||||||
|
|
||||||
} else if (paramMetadata instanceof InjectMetadata) {
|
|
||||||
token = paramMetadata.token;
|
|
||||||
|
|
||||||
} else if (paramMetadata instanceof OptionalMetadata) {
|
|
||||||
optional = true;
|
|
||||||
|
|
||||||
} else if (paramMetadata instanceof SelfMetadata) {
|
|
||||||
upperBoundVisibility = paramMetadata;
|
|
||||||
|
|
||||||
} else if (paramMetadata instanceof HostMetadata) {
|
|
||||||
upperBoundVisibility = paramMetadata;
|
|
||||||
|
|
||||||
} else if (paramMetadata instanceof SkipSelfMetadata) {
|
|
||||||
lowerBoundVisibility = paramMetadata;
|
|
||||||
|
|
||||||
} else if (paramMetadata instanceof DependencyMetadata) {
|
|
||||||
if (isPresent(paramMetadata.token)) {
|
|
||||||
token = paramMetadata.token;
|
|
||||||
}
|
|
||||||
depProps.push(paramMetadata);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
token = resolveForwardRef(token);
|
|
||||||
|
|
||||||
if (isPresent(token)) {
|
|
||||||
return _createDependency(token, optional, lowerBoundVisibility, upperBoundVisibility, depProps);
|
|
||||||
} else {
|
|
||||||
throw new NoAnnotationError(typeOrFunc, params);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function _createDependency(token, optional, lowerBoundVisibility, upperBoundVisibility,
|
|
||||||
depProps): Dependency {
|
|
||||||
return new Dependency(Key.get(token), optional, lowerBoundVisibility, upperBoundVisibility,
|
|
||||||
depProps);
|
|
||||||
}
|
}
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
import {ListWrapper} from 'angular2/src/facade/collection';
|
import {ListWrapper} from 'angular2/src/facade/collection';
|
||||||
import {stringify, isBlank} from 'angular2/src/facade/lang';
|
import {stringify, isBlank} from 'angular2/src/facade/lang';
|
||||||
import {BaseException, WrappedException, unimplemented} from 'angular2/src/facade/exceptions';
|
import {BaseException, WrappedException, unimplemented} from 'angular2/src/facade/exceptions';
|
||||||
import {Key} from './key';
|
import {ReflectiveKey} from './reflective_key';
|
||||||
import {Injector} from './injector';
|
import {ReflectiveInjector} from './reflective_injector';
|
||||||
|
|
||||||
function findFirstClosedCycle(keys: any[]): any[] {
|
function findFirstClosedCycle(keys: any[]): any[] {
|
||||||
var res = [];
|
var res = [];
|
||||||
@ -36,15 +36,16 @@ export class AbstractProviderError extends BaseException {
|
|||||||
message: string;
|
message: string;
|
||||||
|
|
||||||
/** @internal */
|
/** @internal */
|
||||||
keys: Key[];
|
keys: ReflectiveKey[];
|
||||||
|
|
||||||
/** @internal */
|
/** @internal */
|
||||||
injectors: Injector[];
|
injectors: ReflectiveInjector[];
|
||||||
|
|
||||||
/** @internal */
|
/** @internal */
|
||||||
constructResolvingMessage: Function;
|
constructResolvingMessage: Function;
|
||||||
|
|
||||||
constructor(injector: Injector, key: Key, constructResolvingMessage: Function) {
|
constructor(injector: ReflectiveInjector, key: ReflectiveKey,
|
||||||
|
constructResolvingMessage: Function) {
|
||||||
super("DI Exception");
|
super("DI Exception");
|
||||||
this.keys = [key];
|
this.keys = [key];
|
||||||
this.injectors = [injector];
|
this.injectors = [injector];
|
||||||
@ -52,7 +53,7 @@ export class AbstractProviderError extends BaseException {
|
|||||||
this.message = this.constructResolvingMessage(this.keys);
|
this.message = this.constructResolvingMessage(this.keys);
|
||||||
}
|
}
|
||||||
|
|
||||||
addKey(injector: Injector, key: Key): void {
|
addKey(injector: ReflectiveInjector, key: ReflectiveKey): void {
|
||||||
this.injectors.push(injector);
|
this.injectors.push(injector);
|
||||||
this.keys.push(key);
|
this.keys.push(key);
|
||||||
this.message = this.constructResolvingMessage(this.keys);
|
this.message = this.constructResolvingMessage(this.keys);
|
||||||
@ -76,7 +77,7 @@ export class AbstractProviderError extends BaseException {
|
|||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
export class NoProviderError extends AbstractProviderError {
|
export class NoProviderError extends AbstractProviderError {
|
||||||
constructor(injector: Injector, key: Key) {
|
constructor(injector: ReflectiveInjector, key: ReflectiveKey) {
|
||||||
super(injector, key, function(keys: any[]) {
|
super(injector, key, function(keys: any[]) {
|
||||||
var first = stringify(ListWrapper.first(keys).token);
|
var first = stringify(ListWrapper.first(keys).token);
|
||||||
return `No provider for ${first}!${constructResolvingPath(keys)}`;
|
return `No provider for ${first}!${constructResolvingPath(keys)}`;
|
||||||
@ -101,7 +102,7 @@ export class NoProviderError extends AbstractProviderError {
|
|||||||
* Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed.
|
* Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed.
|
||||||
*/
|
*/
|
||||||
export class CyclicDependencyError extends AbstractProviderError {
|
export class CyclicDependencyError extends AbstractProviderError {
|
||||||
constructor(injector: Injector, key: Key) {
|
constructor(injector: ReflectiveInjector, key: ReflectiveKey) {
|
||||||
super(injector, key, function(keys: any[]) {
|
super(injector, key, function(keys: any[]) {
|
||||||
return `Cannot instantiate cyclic dependency!${constructResolvingPath(keys)}`;
|
return `Cannot instantiate cyclic dependency!${constructResolvingPath(keys)}`;
|
||||||
});
|
});
|
||||||
@ -136,18 +137,18 @@ export class CyclicDependencyError extends AbstractProviderError {
|
|||||||
*/
|
*/
|
||||||
export class InstantiationError extends WrappedException {
|
export class InstantiationError extends WrappedException {
|
||||||
/** @internal */
|
/** @internal */
|
||||||
keys: Key[];
|
keys: ReflectiveKey[];
|
||||||
|
|
||||||
/** @internal */
|
/** @internal */
|
||||||
injectors: Injector[];
|
injectors: ReflectiveInjector[];
|
||||||
|
|
||||||
constructor(injector: Injector, originalException, originalStack, key: Key) {
|
constructor(injector: ReflectiveInjector, originalException, originalStack, key: ReflectiveKey) {
|
||||||
super("DI Exception", originalException, originalStack, null);
|
super("DI Exception", originalException, originalStack, null);
|
||||||
this.keys = [key];
|
this.keys = [key];
|
||||||
this.injectors = [injector];
|
this.injectors = [injector];
|
||||||
}
|
}
|
||||||
|
|
||||||
addKey(injector: Injector, key: Key): void {
|
addKey(injector: ReflectiveInjector, key: ReflectiveKey): void {
|
||||||
this.injectors.push(injector);
|
this.injectors.push(injector);
|
||||||
this.keys.push(key);
|
this.keys.push(key);
|
||||||
}
|
}
|
||||||
@ -157,7 +158,7 @@ export class InstantiationError extends WrappedException {
|
|||||||
return `Error during instantiation of ${first}!${constructResolvingPath(this.keys)}.`;
|
return `Error during instantiation of ${first}!${constructResolvingPath(this.keys)}.`;
|
||||||
}
|
}
|
||||||
|
|
||||||
get causeKey(): Key { return this.keys[0]; }
|
get causeKey(): ReflectiveKey { return this.keys[0]; }
|
||||||
|
|
||||||
get context() { return this.injectors[this.injectors.length - 1].debugContext(); }
|
get context() { return this.injectors[this.injectors.length - 1].debugContext(); }
|
||||||
}
|
}
|
887
modules/angular2/src/core/di/reflective_injector.ts
Normal file
887
modules/angular2/src/core/di/reflective_injector.ts
Normal file
@ -0,0 +1,887 @@
|
|||||||
|
import {Map, MapWrapper, ListWrapper} from 'angular2/src/facade/collection';
|
||||||
|
import {Provider, ProviderBuilder, provide} from './provider';
|
||||||
|
import {
|
||||||
|
ResolvedReflectiveProvider,
|
||||||
|
ReflectiveDependency,
|
||||||
|
ResolvedReflectiveFactory,
|
||||||
|
resolveReflectiveProviders
|
||||||
|
} from './reflective_provider';
|
||||||
|
import {
|
||||||
|
AbstractProviderError,
|
||||||
|
NoProviderError,
|
||||||
|
CyclicDependencyError,
|
||||||
|
InstantiationError,
|
||||||
|
InvalidProviderError,
|
||||||
|
OutOfBoundsError
|
||||||
|
} from './reflective_exceptions';
|
||||||
|
import {Type, CONST_EXPR, isPresent} from 'angular2/src/facade/lang';
|
||||||
|
import {BaseException, unimplemented} from 'angular2/src/facade/exceptions';
|
||||||
|
import {ReflectiveKey} from './reflective_key';
|
||||||
|
import {SelfMetadata, HostMetadata, SkipSelfMetadata} from './metadata';
|
||||||
|
import {Injector, THROW_IF_NOT_FOUND} from './injector';
|
||||||
|
|
||||||
|
var __unused: Type; // avoid unused import when Type union types are erased
|
||||||
|
|
||||||
|
// Threshold for the dynamic version
|
||||||
|
const _MAX_CONSTRUCTION_COUNTER = 10;
|
||||||
|
const UNDEFINED = CONST_EXPR(new Object());
|
||||||
|
|
||||||
|
export interface ReflectiveProtoInjectorStrategy {
|
||||||
|
getProviderAtIndex(index: number): ResolvedReflectiveProvider;
|
||||||
|
createInjectorStrategy(inj: ReflectiveInjector_): ReflectiveInjectorStrategy;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ReflectiveProtoInjectorInlineStrategy implements ReflectiveProtoInjectorStrategy {
|
||||||
|
provider0: ResolvedReflectiveProvider = null;
|
||||||
|
provider1: ResolvedReflectiveProvider = null;
|
||||||
|
provider2: ResolvedReflectiveProvider = null;
|
||||||
|
provider3: ResolvedReflectiveProvider = null;
|
||||||
|
provider4: ResolvedReflectiveProvider = null;
|
||||||
|
provider5: ResolvedReflectiveProvider = null;
|
||||||
|
provider6: ResolvedReflectiveProvider = null;
|
||||||
|
provider7: ResolvedReflectiveProvider = null;
|
||||||
|
provider8: ResolvedReflectiveProvider = null;
|
||||||
|
provider9: ResolvedReflectiveProvider = null;
|
||||||
|
|
||||||
|
keyId0: number = null;
|
||||||
|
keyId1: number = null;
|
||||||
|
keyId2: number = null;
|
||||||
|
keyId3: number = null;
|
||||||
|
keyId4: number = null;
|
||||||
|
keyId5: number = null;
|
||||||
|
keyId6: number = null;
|
||||||
|
keyId7: number = null;
|
||||||
|
keyId8: number = null;
|
||||||
|
keyId9: number = null;
|
||||||
|
|
||||||
|
constructor(protoEI: ReflectiveProtoInjector, providers: ResolvedReflectiveProvider[]) {
|
||||||
|
var length = providers.length;
|
||||||
|
|
||||||
|
if (length > 0) {
|
||||||
|
this.provider0 = providers[0];
|
||||||
|
this.keyId0 = providers[0].key.id;
|
||||||
|
}
|
||||||
|
if (length > 1) {
|
||||||
|
this.provider1 = providers[1];
|
||||||
|
this.keyId1 = providers[1].key.id;
|
||||||
|
}
|
||||||
|
if (length > 2) {
|
||||||
|
this.provider2 = providers[2];
|
||||||
|
this.keyId2 = providers[2].key.id;
|
||||||
|
}
|
||||||
|
if (length > 3) {
|
||||||
|
this.provider3 = providers[3];
|
||||||
|
this.keyId3 = providers[3].key.id;
|
||||||
|
}
|
||||||
|
if (length > 4) {
|
||||||
|
this.provider4 = providers[4];
|
||||||
|
this.keyId4 = providers[4].key.id;
|
||||||
|
}
|
||||||
|
if (length > 5) {
|
||||||
|
this.provider5 = providers[5];
|
||||||
|
this.keyId5 = providers[5].key.id;
|
||||||
|
}
|
||||||
|
if (length > 6) {
|
||||||
|
this.provider6 = providers[6];
|
||||||
|
this.keyId6 = providers[6].key.id;
|
||||||
|
}
|
||||||
|
if (length > 7) {
|
||||||
|
this.provider7 = providers[7];
|
||||||
|
this.keyId7 = providers[7].key.id;
|
||||||
|
}
|
||||||
|
if (length > 8) {
|
||||||
|
this.provider8 = providers[8];
|
||||||
|
this.keyId8 = providers[8].key.id;
|
||||||
|
}
|
||||||
|
if (length > 9) {
|
||||||
|
this.provider9 = providers[9];
|
||||||
|
this.keyId9 = providers[9].key.id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getProviderAtIndex(index: number): ResolvedReflectiveProvider {
|
||||||
|
if (index == 0) return this.provider0;
|
||||||
|
if (index == 1) return this.provider1;
|
||||||
|
if (index == 2) return this.provider2;
|
||||||
|
if (index == 3) return this.provider3;
|
||||||
|
if (index == 4) return this.provider4;
|
||||||
|
if (index == 5) return this.provider5;
|
||||||
|
if (index == 6) return this.provider6;
|
||||||
|
if (index == 7) return this.provider7;
|
||||||
|
if (index == 8) return this.provider8;
|
||||||
|
if (index == 9) return this.provider9;
|
||||||
|
throw new OutOfBoundsError(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
createInjectorStrategy(injector: ReflectiveInjector_): ReflectiveInjectorStrategy {
|
||||||
|
return new ReflectiveInjectorInlineStrategy(injector, this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ReflectiveProtoInjectorDynamicStrategy implements ReflectiveProtoInjectorStrategy {
|
||||||
|
keyIds: number[];
|
||||||
|
|
||||||
|
constructor(protoInj: ReflectiveProtoInjector, public providers: ResolvedReflectiveProvider[]) {
|
||||||
|
var len = providers.length;
|
||||||
|
|
||||||
|
this.keyIds = ListWrapper.createFixedSize(len);
|
||||||
|
|
||||||
|
for (var i = 0; i < len; i++) {
|
||||||
|
this.keyIds[i] = providers[i].key.id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getProviderAtIndex(index: number): ResolvedReflectiveProvider {
|
||||||
|
if (index < 0 || index >= this.providers.length) {
|
||||||
|
throw new OutOfBoundsError(index);
|
||||||
|
}
|
||||||
|
return this.providers[index];
|
||||||
|
}
|
||||||
|
|
||||||
|
createInjectorStrategy(ei: ReflectiveInjector_): ReflectiveInjectorStrategy {
|
||||||
|
return new ReflectiveInjectorDynamicStrategy(this, ei);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ReflectiveProtoInjector {
|
||||||
|
static fromResolvedProviders(providers: ResolvedReflectiveProvider[]): ReflectiveProtoInjector {
|
||||||
|
return new ReflectiveProtoInjector(providers);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @internal */
|
||||||
|
_strategy: ReflectiveProtoInjectorStrategy;
|
||||||
|
numberOfProviders: number;
|
||||||
|
|
||||||
|
constructor(providers: ResolvedReflectiveProvider[]) {
|
||||||
|
this.numberOfProviders = providers.length;
|
||||||
|
this._strategy = providers.length > _MAX_CONSTRUCTION_COUNTER ?
|
||||||
|
new ReflectiveProtoInjectorDynamicStrategy(this, providers) :
|
||||||
|
new ReflectiveProtoInjectorInlineStrategy(this, providers);
|
||||||
|
}
|
||||||
|
|
||||||
|
getProviderAtIndex(index: number): ResolvedReflectiveProvider {
|
||||||
|
return this._strategy.getProviderAtIndex(index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export interface ReflectiveInjectorStrategy {
|
||||||
|
getObjByKeyId(keyId: number): any;
|
||||||
|
getObjAtIndex(index: number): any;
|
||||||
|
getMaxNumberOfObjects(): number;
|
||||||
|
|
||||||
|
resetConstructionCounter(): void;
|
||||||
|
instantiateProvider(provider: ResolvedReflectiveProvider): any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ReflectiveInjectorInlineStrategy implements ReflectiveInjectorStrategy {
|
||||||
|
obj0: any = UNDEFINED;
|
||||||
|
obj1: any = UNDEFINED;
|
||||||
|
obj2: any = UNDEFINED;
|
||||||
|
obj3: any = UNDEFINED;
|
||||||
|
obj4: any = UNDEFINED;
|
||||||
|
obj5: any = UNDEFINED;
|
||||||
|
obj6: any = UNDEFINED;
|
||||||
|
obj7: any = UNDEFINED;
|
||||||
|
obj8: any = UNDEFINED;
|
||||||
|
obj9: any = UNDEFINED;
|
||||||
|
|
||||||
|
constructor(public injector: ReflectiveInjector_,
|
||||||
|
public protoStrategy: ReflectiveProtoInjectorInlineStrategy) {}
|
||||||
|
|
||||||
|
resetConstructionCounter(): void { this.injector._constructionCounter = 0; }
|
||||||
|
|
||||||
|
instantiateProvider(provider: ResolvedReflectiveProvider): any {
|
||||||
|
return this.injector._new(provider);
|
||||||
|
}
|
||||||
|
|
||||||
|
getObjByKeyId(keyId: number): any {
|
||||||
|
var p = this.protoStrategy;
|
||||||
|
var inj = this.injector;
|
||||||
|
|
||||||
|
if (p.keyId0 === keyId) {
|
||||||
|
if (this.obj0 === UNDEFINED) {
|
||||||
|
this.obj0 = inj._new(p.provider0);
|
||||||
|
}
|
||||||
|
return this.obj0;
|
||||||
|
}
|
||||||
|
if (p.keyId1 === keyId) {
|
||||||
|
if (this.obj1 === UNDEFINED) {
|
||||||
|
this.obj1 = inj._new(p.provider1);
|
||||||
|
}
|
||||||
|
return this.obj1;
|
||||||
|
}
|
||||||
|
if (p.keyId2 === keyId) {
|
||||||
|
if (this.obj2 === UNDEFINED) {
|
||||||
|
this.obj2 = inj._new(p.provider2);
|
||||||
|
}
|
||||||
|
return this.obj2;
|
||||||
|
}
|
||||||
|
if (p.keyId3 === keyId) {
|
||||||
|
if (this.obj3 === UNDEFINED) {
|
||||||
|
this.obj3 = inj._new(p.provider3);
|
||||||
|
}
|
||||||
|
return this.obj3;
|
||||||
|
}
|
||||||
|
if (p.keyId4 === keyId) {
|
||||||
|
if (this.obj4 === UNDEFINED) {
|
||||||
|
this.obj4 = inj._new(p.provider4);
|
||||||
|
}
|
||||||
|
return this.obj4;
|
||||||
|
}
|
||||||
|
if (p.keyId5 === keyId) {
|
||||||
|
if (this.obj5 === UNDEFINED) {
|
||||||
|
this.obj5 = inj._new(p.provider5);
|
||||||
|
}
|
||||||
|
return this.obj5;
|
||||||
|
}
|
||||||
|
if (p.keyId6 === keyId) {
|
||||||
|
if (this.obj6 === UNDEFINED) {
|
||||||
|
this.obj6 = inj._new(p.provider6);
|
||||||
|
}
|
||||||
|
return this.obj6;
|
||||||
|
}
|
||||||
|
if (p.keyId7 === keyId) {
|
||||||
|
if (this.obj7 === UNDEFINED) {
|
||||||
|
this.obj7 = inj._new(p.provider7);
|
||||||
|
}
|
||||||
|
return this.obj7;
|
||||||
|
}
|
||||||
|
if (p.keyId8 === keyId) {
|
||||||
|
if (this.obj8 === UNDEFINED) {
|
||||||
|
this.obj8 = inj._new(p.provider8);
|
||||||
|
}
|
||||||
|
return this.obj8;
|
||||||
|
}
|
||||||
|
if (p.keyId9 === keyId) {
|
||||||
|
if (this.obj9 === UNDEFINED) {
|
||||||
|
this.obj9 = inj._new(p.provider9);
|
||||||
|
}
|
||||||
|
return this.obj9;
|
||||||
|
}
|
||||||
|
|
||||||
|
return UNDEFINED;
|
||||||
|
}
|
||||||
|
|
||||||
|
getObjAtIndex(index: number): any {
|
||||||
|
if (index == 0) return this.obj0;
|
||||||
|
if (index == 1) return this.obj1;
|
||||||
|
if (index == 2) return this.obj2;
|
||||||
|
if (index == 3) return this.obj3;
|
||||||
|
if (index == 4) return this.obj4;
|
||||||
|
if (index == 5) return this.obj5;
|
||||||
|
if (index == 6) return this.obj6;
|
||||||
|
if (index == 7) return this.obj7;
|
||||||
|
if (index == 8) return this.obj8;
|
||||||
|
if (index == 9) return this.obj9;
|
||||||
|
throw new OutOfBoundsError(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
getMaxNumberOfObjects(): number { return _MAX_CONSTRUCTION_COUNTER; }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export class ReflectiveInjectorDynamicStrategy implements ReflectiveInjectorStrategy {
|
||||||
|
objs: any[];
|
||||||
|
|
||||||
|
constructor(public protoStrategy: ReflectiveProtoInjectorDynamicStrategy,
|
||||||
|
public injector: ReflectiveInjector_) {
|
||||||
|
this.objs = ListWrapper.createFixedSize(protoStrategy.providers.length);
|
||||||
|
ListWrapper.fill(this.objs, UNDEFINED);
|
||||||
|
}
|
||||||
|
|
||||||
|
resetConstructionCounter(): void { this.injector._constructionCounter = 0; }
|
||||||
|
|
||||||
|
instantiateProvider(provider: ResolvedReflectiveProvider): any {
|
||||||
|
return this.injector._new(provider);
|
||||||
|
}
|
||||||
|
|
||||||
|
getObjByKeyId(keyId: number): any {
|
||||||
|
var p = this.protoStrategy;
|
||||||
|
|
||||||
|
for (var i = 0; i < p.keyIds.length; i++) {
|
||||||
|
if (p.keyIds[i] === keyId) {
|
||||||
|
if (this.objs[i] === UNDEFINED) {
|
||||||
|
this.objs[i] = this.injector._new(p.providers[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.objs[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return UNDEFINED;
|
||||||
|
}
|
||||||
|
|
||||||
|
getObjAtIndex(index: number): any {
|
||||||
|
if (index < 0 || index >= this.objs.length) {
|
||||||
|
throw new OutOfBoundsError(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.objs[index];
|
||||||
|
}
|
||||||
|
|
||||||
|
getMaxNumberOfObjects(): number { return this.objs.length; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A ReflectiveDependency injection container used for instantiating objects and resolving
|
||||||
|
* dependencies.
|
||||||
|
*
|
||||||
|
* An `Injector` is a replacement for a `new` operator, which can automatically resolve the
|
||||||
|
* constructor dependencies.
|
||||||
|
*
|
||||||
|
* In typical use, application code asks for the dependencies in the constructor and they are
|
||||||
|
* resolved by the `Injector`.
|
||||||
|
*
|
||||||
|
* ### Example ([live demo](http://plnkr.co/edit/jzjec0?p=preview))
|
||||||
|
*
|
||||||
|
* The following example creates an `Injector` configured to create `Engine` and `Car`.
|
||||||
|
*
|
||||||
|
* ```typescript
|
||||||
|
* @Injectable()
|
||||||
|
* class Engine {
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* @Injectable()
|
||||||
|
* class Car {
|
||||||
|
* constructor(public engine:Engine) {}
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]);
|
||||||
|
* var car = injector.get(Car);
|
||||||
|
* expect(car instanceof Car).toBe(true);
|
||||||
|
* expect(car.engine instanceof Engine).toBe(true);
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* Notice, we don't use the `new` operator because we explicitly want to have the `Injector`
|
||||||
|
* resolve all of the object's dependencies automatically.
|
||||||
|
*/
|
||||||
|
export abstract class ReflectiveInjector implements Injector {
|
||||||
|
/**
|
||||||
|
* Turns an array of provider definitions into an array of resolved providers.
|
||||||
|
*
|
||||||
|
* A resolution is a process of flattening multiple nested arrays and converting individual
|
||||||
|
* providers into an array of {@link ResolvedReflectiveProvider}s.
|
||||||
|
*
|
||||||
|
* ### Example ([live demo](http://plnkr.co/edit/AiXTHi?p=preview))
|
||||||
|
*
|
||||||
|
* ```typescript
|
||||||
|
* @Injectable()
|
||||||
|
* class Engine {
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* @Injectable()
|
||||||
|
* class Car {
|
||||||
|
* constructor(public engine:Engine) {}
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* var providers = ReflectiveInjector.resolve([Car, [[Engine]]]);
|
||||||
|
*
|
||||||
|
* expect(providers.length).toEqual(2);
|
||||||
|
*
|
||||||
|
* expect(providers[0] instanceof ResolvedReflectiveProvider).toBe(true);
|
||||||
|
* expect(providers[0].key.displayName).toBe("Car");
|
||||||
|
* expect(providers[0].dependencies.length).toEqual(1);
|
||||||
|
* expect(providers[0].factory).toBeDefined();
|
||||||
|
*
|
||||||
|
* expect(providers[1].key.displayName).toBe("Engine");
|
||||||
|
* });
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* See {@link ReflectiveInjector#fromResolvedProviders} for more info.
|
||||||
|
*/
|
||||||
|
static resolve(providers: Array<Type | Provider | any[]>): ResolvedReflectiveProvider[] {
|
||||||
|
return resolveReflectiveProviders(providers);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves an array of providers and creates an injector from those providers.
|
||||||
|
*
|
||||||
|
* The passed-in providers can be an array of `Type`, {@link Provider},
|
||||||
|
* or a recursive array of more providers.
|
||||||
|
*
|
||||||
|
* ### Example ([live demo](http://plnkr.co/edit/ePOccA?p=preview))
|
||||||
|
*
|
||||||
|
* ```typescript
|
||||||
|
* @Injectable()
|
||||||
|
* class Engine {
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* @Injectable()
|
||||||
|
* class Car {
|
||||||
|
* constructor(public engine:Engine) {}
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]);
|
||||||
|
* expect(injector.get(Car) instanceof Car).toBe(true);
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* This function is slower than the corresponding `fromResolvedProviders`
|
||||||
|
* because it needs to resolve the passed-in providers first.
|
||||||
|
* See {@link Injector#resolve} and {@link Injector#fromResolvedProviders}.
|
||||||
|
*/
|
||||||
|
static resolveAndCreate(providers: Array<Type | Provider | any[]>,
|
||||||
|
parent: Injector = null): ReflectiveInjector {
|
||||||
|
var ResolvedReflectiveProviders = ReflectiveInjector.resolve(providers);
|
||||||
|
return ReflectiveInjector.fromResolvedProviders(ResolvedReflectiveProviders, parent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates an injector from previously resolved providers.
|
||||||
|
*
|
||||||
|
* This API is the recommended way to construct injectors in performance-sensitive parts.
|
||||||
|
*
|
||||||
|
* ### Example ([live demo](http://plnkr.co/edit/KrSMci?p=preview))
|
||||||
|
*
|
||||||
|
* ```typescript
|
||||||
|
* @Injectable()
|
||||||
|
* class Engine {
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* @Injectable()
|
||||||
|
* class Car {
|
||||||
|
* constructor(public engine:Engine) {}
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* var providers = ReflectiveInjector.resolve([Car, Engine]);
|
||||||
|
* var injector = ReflectiveInjector.fromResolvedProviders(providers);
|
||||||
|
* expect(injector.get(Car) instanceof Car).toBe(true);
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
static fromResolvedProviders(providers: ResolvedReflectiveProvider[],
|
||||||
|
parent: Injector = null): ReflectiveInjector {
|
||||||
|
return new ReflectiveInjector_(ReflectiveProtoInjector.fromResolvedProviders(providers),
|
||||||
|
parent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated
|
||||||
|
*/
|
||||||
|
static fromResolvedBindings(providers: ResolvedReflectiveProvider[]): ReflectiveInjector {
|
||||||
|
return ReflectiveInjector.fromResolvedProviders(providers);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parent of this injector.
|
||||||
|
*
|
||||||
|
* <!-- TODO: Add a link to the section of the user guide talking about hierarchical injection.
|
||||||
|
* -->
|
||||||
|
*
|
||||||
|
* ### Example ([live demo](http://plnkr.co/edit/eosMGo?p=preview))
|
||||||
|
*
|
||||||
|
* ```typescript
|
||||||
|
* var parent = ReflectiveInjector.resolveAndCreate([]);
|
||||||
|
* var child = parent.resolveAndCreateChild([]);
|
||||||
|
* expect(child.parent).toBe(parent);
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
get parent(): Injector { return unimplemented(); }
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @internal
|
||||||
|
*/
|
||||||
|
debugContext(): any { return null; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves an array of providers and creates a child injector from those providers.
|
||||||
|
*
|
||||||
|
* <!-- TODO: Add a link to the section of the user guide talking about hierarchical injection.
|
||||||
|
* -->
|
||||||
|
*
|
||||||
|
* The passed-in providers can be an array of `Type`, {@link Provider},
|
||||||
|
* or a recursive array of more providers.
|
||||||
|
*
|
||||||
|
* ### Example ([live demo](http://plnkr.co/edit/opB3T4?p=preview))
|
||||||
|
*
|
||||||
|
* ```typescript
|
||||||
|
* class ParentProvider {}
|
||||||
|
* class ChildProvider {}
|
||||||
|
*
|
||||||
|
* var parent = ReflectiveInjector.resolveAndCreate([ParentProvider]);
|
||||||
|
* var child = parent.resolveAndCreateChild([ChildProvider]);
|
||||||
|
*
|
||||||
|
* expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true);
|
||||||
|
* expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true);
|
||||||
|
* expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider));
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* This function is slower than the corresponding `createChildFromResolved`
|
||||||
|
* because it needs to resolve the passed-in providers first.
|
||||||
|
* See {@link Injector#resolve} and {@link Injector#createChildFromResolved}.
|
||||||
|
*/
|
||||||
|
resolveAndCreateChild(providers: Array<Type | Provider | any[]>): ReflectiveInjector {
|
||||||
|
return unimplemented();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a child injector from previously resolved providers.
|
||||||
|
*
|
||||||
|
* <!-- TODO: Add a link to the section of the user guide talking about hierarchical injection.
|
||||||
|
* -->
|
||||||
|
*
|
||||||
|
* This API is the recommended way to construct injectors in performance-sensitive parts.
|
||||||
|
*
|
||||||
|
* ### Example ([live demo](http://plnkr.co/edit/VhyfjN?p=preview))
|
||||||
|
*
|
||||||
|
* ```typescript
|
||||||
|
* class ParentProvider {}
|
||||||
|
* class ChildProvider {}
|
||||||
|
*
|
||||||
|
* var parentProviders = ReflectiveInjector.resolve([ParentProvider]);
|
||||||
|
* var childProviders = ReflectiveInjector.resolve([ChildProvider]);
|
||||||
|
*
|
||||||
|
* var parent = ReflectiveInjector.fromResolvedProviders(parentProviders);
|
||||||
|
* var child = parent.createChildFromResolved(childProviders);
|
||||||
|
*
|
||||||
|
* expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true);
|
||||||
|
* expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true);
|
||||||
|
* expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider));
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
createChildFromResolved(providers: ResolvedReflectiveProvider[]): ReflectiveInjector {
|
||||||
|
return unimplemented();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves a provider and instantiates an object in the context of the injector.
|
||||||
|
*
|
||||||
|
* The created object does not get cached by the injector.
|
||||||
|
*
|
||||||
|
* ### Example ([live demo](http://plnkr.co/edit/yvVXoB?p=preview))
|
||||||
|
*
|
||||||
|
* ```typescript
|
||||||
|
* @Injectable()
|
||||||
|
* class Engine {
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* @Injectable()
|
||||||
|
* class Car {
|
||||||
|
* constructor(public engine:Engine) {}
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* var injector = ReflectiveInjector.resolveAndCreate([Engine]);
|
||||||
|
*
|
||||||
|
* var car = injector.resolveAndInstantiate(Car);
|
||||||
|
* expect(car.engine).toBe(injector.get(Engine));
|
||||||
|
* expect(car).not.toBe(injector.resolveAndInstantiate(Car));
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
resolveAndInstantiate(provider: Type | Provider): any { return unimplemented(); }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Instantiates an object using a resolved provider in the context of the injector.
|
||||||
|
*
|
||||||
|
* The created object does not get cached by the injector.
|
||||||
|
*
|
||||||
|
* ### Example ([live demo](http://plnkr.co/edit/ptCImQ?p=preview))
|
||||||
|
*
|
||||||
|
* ```typescript
|
||||||
|
* @Injectable()
|
||||||
|
* class Engine {
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* @Injectable()
|
||||||
|
* class Car {
|
||||||
|
* constructor(public engine:Engine) {}
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* var injector = ReflectiveInjector.resolveAndCreate([Engine]);
|
||||||
|
* var carProvider = ReflectiveInjector.resolve([Car])[0];
|
||||||
|
* var car = injector.instantiateResolved(carProvider);
|
||||||
|
* expect(car.engine).toBe(injector.get(Engine));
|
||||||
|
* expect(car).not.toBe(injector.instantiateResolved(carProvider));
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
instantiateResolved(provider: ResolvedReflectiveProvider): any { return unimplemented(); }
|
||||||
|
|
||||||
|
abstract get(token: any, notFoundValue?: any): any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ReflectiveInjector_ implements ReflectiveInjector {
|
||||||
|
private _strategy: ReflectiveInjectorStrategy;
|
||||||
|
/** @internal */
|
||||||
|
_constructionCounter: number = 0;
|
||||||
|
/** @internal */
|
||||||
|
public _proto: any /* ProtoInjector */;
|
||||||
|
/** @internal */
|
||||||
|
public _parent: Injector;
|
||||||
|
/**
|
||||||
|
* Private
|
||||||
|
*/
|
||||||
|
constructor(_proto: any /* ProtoInjector */, _parent: Injector = null,
|
||||||
|
private _debugContext: Function = null) {
|
||||||
|
this._proto = _proto;
|
||||||
|
this._parent = _parent;
|
||||||
|
this._strategy = _proto._strategy.createInjectorStrategy(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @internal
|
||||||
|
*/
|
||||||
|
debugContext(): any { return this._debugContext(); }
|
||||||
|
|
||||||
|
get(token: any, notFoundValue: any = THROW_IF_NOT_FOUND): any {
|
||||||
|
return this._getByKey(ReflectiveKey.get(token), null, null, notFoundValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
getAt(index: number): any { return this._strategy.getObjAtIndex(index); }
|
||||||
|
|
||||||
|
get parent(): Injector { return this._parent; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @internal
|
||||||
|
* Internal. Do not use.
|
||||||
|
* We return `any` not to export the InjectorStrategy type.
|
||||||
|
*/
|
||||||
|
get internalStrategy(): any { return this._strategy; }
|
||||||
|
|
||||||
|
resolveAndCreateChild(providers: Array<Type | Provider | any[]>): ReflectiveInjector {
|
||||||
|
var ResolvedReflectiveProviders = ReflectiveInjector.resolve(providers);
|
||||||
|
return this.createChildFromResolved(ResolvedReflectiveProviders);
|
||||||
|
}
|
||||||
|
|
||||||
|
createChildFromResolved(providers: ResolvedReflectiveProvider[]): ReflectiveInjector {
|
||||||
|
var proto = new ReflectiveProtoInjector(providers);
|
||||||
|
var inj = new ReflectiveInjector_(proto);
|
||||||
|
inj._parent = this;
|
||||||
|
return inj;
|
||||||
|
}
|
||||||
|
|
||||||
|
resolveAndInstantiate(provider: Type | Provider): any {
|
||||||
|
return this.instantiateResolved(ReflectiveInjector.resolve([provider])[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
instantiateResolved(provider: ResolvedReflectiveProvider): any {
|
||||||
|
return this._instantiateProvider(provider);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @internal */
|
||||||
|
_new(provider: ResolvedReflectiveProvider): any {
|
||||||
|
if (this._constructionCounter++ > this._strategy.getMaxNumberOfObjects()) {
|
||||||
|
throw new CyclicDependencyError(this, provider.key);
|
||||||
|
}
|
||||||
|
return this._instantiateProvider(provider);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _instantiateProvider(provider: ResolvedReflectiveProvider): any {
|
||||||
|
if (provider.multiProvider) {
|
||||||
|
var res = ListWrapper.createFixedSize(provider.resolvedFactories.length);
|
||||||
|
for (var i = 0; i < provider.resolvedFactories.length; ++i) {
|
||||||
|
res[i] = this._instantiate(provider, provider.resolvedFactories[i]);
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
} else {
|
||||||
|
return this._instantiate(provider, provider.resolvedFactories[0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _instantiate(provider: ResolvedReflectiveProvider,
|
||||||
|
ResolvedReflectiveFactory: ResolvedReflectiveFactory): any {
|
||||||
|
var factory = ResolvedReflectiveFactory.factory;
|
||||||
|
var deps = ResolvedReflectiveFactory.dependencies;
|
||||||
|
var length = deps.length;
|
||||||
|
|
||||||
|
var d0: any;
|
||||||
|
var d1: any;
|
||||||
|
var d2: any;
|
||||||
|
var d3: any;
|
||||||
|
var d4: any;
|
||||||
|
var d5: any;
|
||||||
|
var d6: any;
|
||||||
|
var d7: any;
|
||||||
|
var d8: any;
|
||||||
|
var d9: any;
|
||||||
|
var d10: any;
|
||||||
|
var d11: any;
|
||||||
|
var d12: any;
|
||||||
|
var d13: any;
|
||||||
|
var d14: any;
|
||||||
|
var d15: any;
|
||||||
|
var d16: any;
|
||||||
|
var d17: any;
|
||||||
|
var d18: any;
|
||||||
|
var d19: any;
|
||||||
|
try {
|
||||||
|
d0 = length > 0 ? this._getByReflectiveDependency(provider, deps[0]) : null;
|
||||||
|
d1 = length > 1 ? this._getByReflectiveDependency(provider, deps[1]) : null;
|
||||||
|
d2 = length > 2 ? this._getByReflectiveDependency(provider, deps[2]) : null;
|
||||||
|
d3 = length > 3 ? this._getByReflectiveDependency(provider, deps[3]) : null;
|
||||||
|
d4 = length > 4 ? this._getByReflectiveDependency(provider, deps[4]) : null;
|
||||||
|
d5 = length > 5 ? this._getByReflectiveDependency(provider, deps[5]) : null;
|
||||||
|
d6 = length > 6 ? this._getByReflectiveDependency(provider, deps[6]) : null;
|
||||||
|
d7 = length > 7 ? this._getByReflectiveDependency(provider, deps[7]) : null;
|
||||||
|
d8 = length > 8 ? this._getByReflectiveDependency(provider, deps[8]) : null;
|
||||||
|
d9 = length > 9 ? this._getByReflectiveDependency(provider, deps[9]) : null;
|
||||||
|
d10 = length > 10 ? this._getByReflectiveDependency(provider, deps[10]) : null;
|
||||||
|
d11 = length > 11 ? this._getByReflectiveDependency(provider, deps[11]) : null;
|
||||||
|
d12 = length > 12 ? this._getByReflectiveDependency(provider, deps[12]) : null;
|
||||||
|
d13 = length > 13 ? this._getByReflectiveDependency(provider, deps[13]) : null;
|
||||||
|
d14 = length > 14 ? this._getByReflectiveDependency(provider, deps[14]) : null;
|
||||||
|
d15 = length > 15 ? this._getByReflectiveDependency(provider, deps[15]) : null;
|
||||||
|
d16 = length > 16 ? this._getByReflectiveDependency(provider, deps[16]) : null;
|
||||||
|
d17 = length > 17 ? this._getByReflectiveDependency(provider, deps[17]) : null;
|
||||||
|
d18 = length > 18 ? this._getByReflectiveDependency(provider, deps[18]) : null;
|
||||||
|
d19 = length > 19 ? this._getByReflectiveDependency(provider, deps[19]) : null;
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof AbstractProviderError || e instanceof InstantiationError) {
|
||||||
|
e.addKey(this, provider.key);
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
var obj;
|
||||||
|
try {
|
||||||
|
switch (length) {
|
||||||
|
case 0:
|
||||||
|
obj = factory();
|
||||||
|
break;
|
||||||
|
case 1:
|
||||||
|
obj = factory(d0);
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
obj = factory(d0, d1);
|
||||||
|
break;
|
||||||
|
case 3:
|
||||||
|
obj = factory(d0, d1, d2);
|
||||||
|
break;
|
||||||
|
case 4:
|
||||||
|
obj = factory(d0, d1, d2, d3);
|
||||||
|
break;
|
||||||
|
case 5:
|
||||||
|
obj = factory(d0, d1, d2, d3, d4);
|
||||||
|
break;
|
||||||
|
case 6:
|
||||||
|
obj = factory(d0, d1, d2, d3, d4, d5);
|
||||||
|
break;
|
||||||
|
case 7:
|
||||||
|
obj = factory(d0, d1, d2, d3, d4, d5, d6);
|
||||||
|
break;
|
||||||
|
case 8:
|
||||||
|
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7);
|
||||||
|
break;
|
||||||
|
case 9:
|
||||||
|
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8);
|
||||||
|
break;
|
||||||
|
case 10:
|
||||||
|
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9);
|
||||||
|
break;
|
||||||
|
case 11:
|
||||||
|
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10);
|
||||||
|
break;
|
||||||
|
case 12:
|
||||||
|
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11);
|
||||||
|
break;
|
||||||
|
case 13:
|
||||||
|
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12);
|
||||||
|
break;
|
||||||
|
case 14:
|
||||||
|
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13);
|
||||||
|
break;
|
||||||
|
case 15:
|
||||||
|
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14);
|
||||||
|
break;
|
||||||
|
case 16:
|
||||||
|
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15);
|
||||||
|
break;
|
||||||
|
case 17:
|
||||||
|
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16);
|
||||||
|
break;
|
||||||
|
case 18:
|
||||||
|
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16,
|
||||||
|
d17);
|
||||||
|
break;
|
||||||
|
case 19:
|
||||||
|
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16,
|
||||||
|
d17, d18);
|
||||||
|
break;
|
||||||
|
case 20:
|
||||||
|
obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16,
|
||||||
|
d17, d18, d19);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new BaseException(
|
||||||
|
`Cannot instantiate '${provider.key.displayName}' because it has more than 20 dependencies`);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
throw new InstantiationError(this, e, e.stack, provider.key);
|
||||||
|
}
|
||||||
|
return obj;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _getByReflectiveDependency(provider: ResolvedReflectiveProvider,
|
||||||
|
dep: ReflectiveDependency): any {
|
||||||
|
return this._getByKey(dep.key, dep.lowerBoundVisibility, dep.upperBoundVisibility,
|
||||||
|
dep.optional ? null : THROW_IF_NOT_FOUND);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _getByKey(key: ReflectiveKey, lowerBoundVisibility: Object, upperBoundVisibility: Object,
|
||||||
|
notFoundValue: any): any {
|
||||||
|
if (key === INJECTOR_KEY) {
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (upperBoundVisibility instanceof SelfMetadata) {
|
||||||
|
return this._getByKeySelf(key, notFoundValue);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
return this._getByKeyDefault(key, notFoundValue, lowerBoundVisibility);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @internal */
|
||||||
|
_throwOrNull(key: ReflectiveKey, notFoundValue: any): any {
|
||||||
|
if (notFoundValue !== THROW_IF_NOT_FOUND) {
|
||||||
|
return notFoundValue;
|
||||||
|
} else {
|
||||||
|
throw new NoProviderError(this, key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @internal */
|
||||||
|
_getByKeySelf(key: ReflectiveKey, notFoundValue: any): any {
|
||||||
|
var obj = this._strategy.getObjByKeyId(key.id);
|
||||||
|
return (obj !== UNDEFINED) ? obj : this._throwOrNull(key, notFoundValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @internal */
|
||||||
|
_getByKeyDefault(key: ReflectiveKey, notFoundValue: any, lowerBoundVisibility: Object): any {
|
||||||
|
var inj: Injector;
|
||||||
|
|
||||||
|
if (lowerBoundVisibility instanceof SkipSelfMetadata) {
|
||||||
|
inj = this._parent;
|
||||||
|
} else {
|
||||||
|
inj = this;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (inj instanceof ReflectiveInjector_) {
|
||||||
|
var inj_ = <ReflectiveInjector_>inj;
|
||||||
|
var obj = inj_._strategy.getObjByKeyId(key.id);
|
||||||
|
if (obj !== UNDEFINED) return obj;
|
||||||
|
inj = inj_._parent;
|
||||||
|
}
|
||||||
|
if (inj !== null) {
|
||||||
|
return inj.get(key.token, notFoundValue);
|
||||||
|
} else {
|
||||||
|
return this._throwOrNull(key, notFoundValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
get displayName(): string {
|
||||||
|
return `ReflectiveInjector(providers: [${_mapProviders(this, (b: ResolvedReflectiveProvider) => ` "${b.key.displayName}" `).join(", ")}])`;
|
||||||
|
}
|
||||||
|
|
||||||
|
toString(): string { return this.displayName; }
|
||||||
|
}
|
||||||
|
|
||||||
|
var INJECTOR_KEY = ReflectiveKey.get(Injector);
|
||||||
|
|
||||||
|
function _mapProviders(injector: ReflectiveInjector_, fn: Function): any[] {
|
||||||
|
var res = [];
|
||||||
|
for (var i = 0; i < injector._proto.numberOfProviders; ++i) {
|
||||||
|
res.push(fn(injector._proto.getProviderAtIndex(i)));
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
@ -3,19 +3,21 @@ import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
|
|||||||
import {resolveForwardRef} from './forward_ref';
|
import {resolveForwardRef} from './forward_ref';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A unique object used for retrieving items from the {@link Injector}.
|
* A unique object used for retrieving items from the {@link ReflectiveInjector}.
|
||||||
*
|
*
|
||||||
* Keys have:
|
* Keys have:
|
||||||
* - a system-wide unique `id`.
|
* - a system-wide unique `id`.
|
||||||
* - a `token`.
|
* - a `token`.
|
||||||
*
|
*
|
||||||
* `Key` is used internally by {@link Injector} because its system-wide unique `id` allows the
|
* `Key` is used internally by {@link ReflectiveInjector} because its system-wide unique `id` allows
|
||||||
|
* the
|
||||||
* injector to store created objects in a more efficient way.
|
* injector to store created objects in a more efficient way.
|
||||||
*
|
*
|
||||||
* `Key` should not be created directly. {@link Injector} creates keys automatically when resolving
|
* `Key` should not be created directly. {@link ReflectiveInjector} creates keys automatically when
|
||||||
|
* resolving
|
||||||
* providers.
|
* providers.
|
||||||
*/
|
*/
|
||||||
export class Key {
|
export class ReflectiveKey {
|
||||||
/**
|
/**
|
||||||
* Private
|
* Private
|
||||||
*/
|
*/
|
||||||
@ -33,7 +35,9 @@ export class Key {
|
|||||||
/**
|
/**
|
||||||
* Retrieves a `Key` for a token.
|
* Retrieves a `Key` for a token.
|
||||||
*/
|
*/
|
||||||
static get(token: Object): Key { return _globalKeyRegistry.get(resolveForwardRef(token)); }
|
static get(token: Object): ReflectiveKey {
|
||||||
|
return _globalKeyRegistry.get(resolveForwardRef(token));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @returns the number of keys registered in the system.
|
* @returns the number of keys registered in the system.
|
||||||
@ -45,16 +49,16 @@ export class Key {
|
|||||||
* @internal
|
* @internal
|
||||||
*/
|
*/
|
||||||
export class KeyRegistry {
|
export class KeyRegistry {
|
||||||
private _allKeys = new Map<Object, Key>();
|
private _allKeys = new Map<Object, ReflectiveKey>();
|
||||||
|
|
||||||
get(token: Object): Key {
|
get(token: Object): ReflectiveKey {
|
||||||
if (token instanceof Key) return token;
|
if (token instanceof ReflectiveKey) return token;
|
||||||
|
|
||||||
if (this._allKeys.has(token)) {
|
if (this._allKeys.has(token)) {
|
||||||
return this._allKeys.get(token);
|
return this._allKeys.get(token);
|
||||||
}
|
}
|
||||||
|
|
||||||
var newKey = new Key(token, Key.numberOfKeys);
|
var newKey = new ReflectiveKey(token, ReflectiveKey.numberOfKeys);
|
||||||
this._allKeys.set(token, newKey);
|
this._allKeys.set(token, newKey);
|
||||||
return newKey;
|
return newKey;
|
||||||
}
|
}
|
292
modules/angular2/src/core/di/reflective_provider.ts
Normal file
292
modules/angular2/src/core/di/reflective_provider.ts
Normal file
@ -0,0 +1,292 @@
|
|||||||
|
import {
|
||||||
|
Type,
|
||||||
|
isBlank,
|
||||||
|
isPresent,
|
||||||
|
CONST,
|
||||||
|
CONST_EXPR,
|
||||||
|
isArray,
|
||||||
|
isType
|
||||||
|
} from 'angular2/src/facade/lang';
|
||||||
|
import {MapWrapper, ListWrapper} from 'angular2/src/facade/collection';
|
||||||
|
import {reflector} from 'angular2/src/core/reflection/reflection';
|
||||||
|
import {ReflectiveKey} from './reflective_key';
|
||||||
|
import {
|
||||||
|
InjectMetadata,
|
||||||
|
InjectableMetadata,
|
||||||
|
OptionalMetadata,
|
||||||
|
SelfMetadata,
|
||||||
|
HostMetadata,
|
||||||
|
SkipSelfMetadata,
|
||||||
|
DependencyMetadata
|
||||||
|
} from './metadata';
|
||||||
|
import {
|
||||||
|
NoAnnotationError,
|
||||||
|
MixingMultiProvidersWithRegularProvidersError,
|
||||||
|
InvalidProviderError
|
||||||
|
} from './reflective_exceptions';
|
||||||
|
import {resolveForwardRef} from './forward_ref';
|
||||||
|
import {Provider, ProviderBuilder, provide} from './provider';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `Dependency` is used by the framework to extend DI.
|
||||||
|
* This is internal to Angular and should not be used directly.
|
||||||
|
*/
|
||||||
|
export class ReflectiveDependency {
|
||||||
|
constructor(public key: ReflectiveKey, public optional: boolean, public lowerBoundVisibility: any,
|
||||||
|
public upperBoundVisibility: any, public properties: any[]) {}
|
||||||
|
|
||||||
|
static fromKey(key: ReflectiveKey): ReflectiveDependency {
|
||||||
|
return new ReflectiveDependency(key, false, null, null, []);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const _EMPTY_LIST = CONST_EXPR([]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An internal resolved representation of a {@link Provider} used by the {@link Injector}.
|
||||||
|
*
|
||||||
|
* It is usually created automatically by `Injector.resolveAndCreate`.
|
||||||
|
*
|
||||||
|
* It can be created manually, as follows:
|
||||||
|
*
|
||||||
|
* ### Example ([live demo](http://plnkr.co/edit/RfEnhh8kUEI0G3qsnIeT?p%3Dpreview&p=preview))
|
||||||
|
*
|
||||||
|
* ```typescript
|
||||||
|
* var resolvedProviders = Injector.resolve([new Provider('message', {useValue: 'Hello'})]);
|
||||||
|
* var injector = Injector.fromResolvedProviders(resolvedProviders);
|
||||||
|
*
|
||||||
|
* expect(injector.get('message')).toEqual('Hello');
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export interface ResolvedReflectiveProvider {
|
||||||
|
/**
|
||||||
|
* A key, usually a `Type`.
|
||||||
|
*/
|
||||||
|
key: ReflectiveKey;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Factory function which can return an instance of an object represented by a key.
|
||||||
|
*/
|
||||||
|
resolvedFactories: ResolvedReflectiveFactory[];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicates if the provider is a multi-provider or a regular provider.
|
||||||
|
*/
|
||||||
|
multiProvider: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* See {@link ResolvedProvider} instead.
|
||||||
|
*
|
||||||
|
* @deprecated
|
||||||
|
*/
|
||||||
|
export interface ResolvedReflectiveBinding extends ResolvedReflectiveProvider {}
|
||||||
|
|
||||||
|
export class ResolvedReflectiveProvider_ implements ResolvedReflectiveBinding {
|
||||||
|
constructor(public key: ReflectiveKey, public resolvedFactories: ResolvedReflectiveFactory[],
|
||||||
|
public multiProvider: boolean) {}
|
||||||
|
|
||||||
|
get resolvedFactory(): ResolvedReflectiveFactory { return this.resolvedFactories[0]; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An internal resolved representation of a factory function created by resolving {@link Provider}.
|
||||||
|
*/
|
||||||
|
export class ResolvedReflectiveFactory {
|
||||||
|
constructor(
|
||||||
|
/**
|
||||||
|
* Factory function which can return an instance of an object represented by a key.
|
||||||
|
*/
|
||||||
|
public factory: Function,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Arguments (dependencies) to the `factory` function.
|
||||||
|
*/
|
||||||
|
public dependencies: ReflectiveDependency[]) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a single provider.
|
||||||
|
*/
|
||||||
|
export function resolveReflectiveFactory(provider: Provider): ResolvedReflectiveFactory {
|
||||||
|
var factoryFn: Function;
|
||||||
|
var resolvedDeps;
|
||||||
|
if (isPresent(provider.useClass)) {
|
||||||
|
var useClass = resolveForwardRef(provider.useClass);
|
||||||
|
factoryFn = reflector.factory(useClass);
|
||||||
|
resolvedDeps = _dependenciesFor(useClass);
|
||||||
|
} else if (isPresent(provider.useExisting)) {
|
||||||
|
factoryFn = (aliasInstance) => aliasInstance;
|
||||||
|
resolvedDeps = [ReflectiveDependency.fromKey(ReflectiveKey.get(provider.useExisting))];
|
||||||
|
} else if (isPresent(provider.useFactory)) {
|
||||||
|
factoryFn = provider.useFactory;
|
||||||
|
resolvedDeps = constructDependencies(provider.useFactory, provider.dependencies);
|
||||||
|
} else {
|
||||||
|
factoryFn = () => provider.useValue;
|
||||||
|
resolvedDeps = _EMPTY_LIST;
|
||||||
|
}
|
||||||
|
return new ResolvedReflectiveFactory(factoryFn, resolvedDeps);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts the {@link Provider} into {@link ResolvedProvider}.
|
||||||
|
*
|
||||||
|
* {@link Injector} internally only uses {@link ResolvedProvider}, {@link Provider} contains
|
||||||
|
* convenience provider syntax.
|
||||||
|
*/
|
||||||
|
export function resolveReflectiveProvider(provider: Provider): ResolvedReflectiveProvider {
|
||||||
|
return new ResolvedReflectiveProvider_(ReflectiveKey.get(provider.token),
|
||||||
|
[resolveReflectiveFactory(provider)], provider.multi);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a list of Providers.
|
||||||
|
*/
|
||||||
|
export function resolveReflectiveProviders(
|
||||||
|
providers: Array<Type | Provider | any[]>): ResolvedReflectiveProvider[] {
|
||||||
|
var normalized = _normalizeProviders(providers, []);
|
||||||
|
var resolved = normalized.map(resolveReflectiveProvider);
|
||||||
|
return MapWrapper.values(
|
||||||
|
mergeResolvedReflectiveProviders(resolved, new Map<number, ResolvedReflectiveProvider>()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Merges a list of ResolvedProviders into a list where
|
||||||
|
* each key is contained exactly once and multi providers
|
||||||
|
* have been merged.
|
||||||
|
*/
|
||||||
|
export function mergeResolvedReflectiveProviders(
|
||||||
|
providers: ResolvedReflectiveProvider[],
|
||||||
|
normalizedProvidersMap: Map<number, ResolvedReflectiveProvider>):
|
||||||
|
Map<number, ResolvedReflectiveProvider> {
|
||||||
|
for (var i = 0; i < providers.length; i++) {
|
||||||
|
var provider = providers[i];
|
||||||
|
var existing = normalizedProvidersMap.get(provider.key.id);
|
||||||
|
if (isPresent(existing)) {
|
||||||
|
if (provider.multiProvider !== existing.multiProvider) {
|
||||||
|
throw new MixingMultiProvidersWithRegularProvidersError(existing, provider);
|
||||||
|
}
|
||||||
|
if (provider.multiProvider) {
|
||||||
|
for (var j = 0; j < provider.resolvedFactories.length; j++) {
|
||||||
|
existing.resolvedFactories.push(provider.resolvedFactories[j]);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
normalizedProvidersMap.set(provider.key.id, provider);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
var resolvedProvider;
|
||||||
|
if (provider.multiProvider) {
|
||||||
|
resolvedProvider = new ResolvedReflectiveProvider_(
|
||||||
|
provider.key, ListWrapper.clone(provider.resolvedFactories), provider.multiProvider);
|
||||||
|
} else {
|
||||||
|
resolvedProvider = provider;
|
||||||
|
}
|
||||||
|
normalizedProvidersMap.set(provider.key.id, resolvedProvider);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return normalizedProvidersMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
function _normalizeProviders(providers: Array<Type | Provider | ProviderBuilder | any[]>,
|
||||||
|
res: Provider[]): Provider[] {
|
||||||
|
providers.forEach(b => {
|
||||||
|
if (b instanceof Type) {
|
||||||
|
res.push(provide(b, {useClass: b}));
|
||||||
|
|
||||||
|
} else if (b instanceof Provider) {
|
||||||
|
res.push(b);
|
||||||
|
|
||||||
|
} else if (b instanceof Array) {
|
||||||
|
_normalizeProviders(b, res);
|
||||||
|
|
||||||
|
} else if (b instanceof ProviderBuilder) {
|
||||||
|
throw new InvalidProviderError(b.token);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
throw new InvalidProviderError(b);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function constructDependencies(typeOrFunc: any,
|
||||||
|
dependencies: any[]): ReflectiveDependency[] {
|
||||||
|
if (isBlank(dependencies)) {
|
||||||
|
return _dependenciesFor(typeOrFunc);
|
||||||
|
} else {
|
||||||
|
var params: any[][] = dependencies.map(t => [t]);
|
||||||
|
return dependencies.map(t => _extractToken(typeOrFunc, t, params));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function _dependenciesFor(typeOrFunc: any): ReflectiveDependency[] {
|
||||||
|
var params = reflector.parameters(typeOrFunc);
|
||||||
|
if (isBlank(params)) return [];
|
||||||
|
if (params.some(isBlank)) {
|
||||||
|
throw new NoAnnotationError(typeOrFunc, params);
|
||||||
|
}
|
||||||
|
return params.map((p: any[]) => _extractToken(typeOrFunc, p, params));
|
||||||
|
}
|
||||||
|
|
||||||
|
function _extractToken(typeOrFunc, metadata /*any[] | any*/,
|
||||||
|
params: any[][]): ReflectiveDependency {
|
||||||
|
var depProps = [];
|
||||||
|
var token = null;
|
||||||
|
var optional = false;
|
||||||
|
|
||||||
|
if (!isArray(metadata)) {
|
||||||
|
if (metadata instanceof InjectMetadata) {
|
||||||
|
return _createDependency(metadata.token, optional, null, null, depProps);
|
||||||
|
} else {
|
||||||
|
return _createDependency(metadata, optional, null, null, depProps);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var lowerBoundVisibility = null;
|
||||||
|
var upperBoundVisibility = null;
|
||||||
|
|
||||||
|
for (var i = 0; i < metadata.length; ++i) {
|
||||||
|
var paramMetadata = metadata[i];
|
||||||
|
|
||||||
|
if (paramMetadata instanceof Type) {
|
||||||
|
token = paramMetadata;
|
||||||
|
|
||||||
|
} else if (paramMetadata instanceof InjectMetadata) {
|
||||||
|
token = paramMetadata.token;
|
||||||
|
|
||||||
|
} else if (paramMetadata instanceof OptionalMetadata) {
|
||||||
|
optional = true;
|
||||||
|
|
||||||
|
} else if (paramMetadata instanceof SelfMetadata) {
|
||||||
|
upperBoundVisibility = paramMetadata;
|
||||||
|
|
||||||
|
} else if (paramMetadata instanceof HostMetadata) {
|
||||||
|
upperBoundVisibility = paramMetadata;
|
||||||
|
|
||||||
|
} else if (paramMetadata instanceof SkipSelfMetadata) {
|
||||||
|
lowerBoundVisibility = paramMetadata;
|
||||||
|
|
||||||
|
} else if (paramMetadata instanceof DependencyMetadata) {
|
||||||
|
if (isPresent(paramMetadata.token)) {
|
||||||
|
token = paramMetadata.token;
|
||||||
|
}
|
||||||
|
depProps.push(paramMetadata);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
token = resolveForwardRef(token);
|
||||||
|
|
||||||
|
if (isPresent(token)) {
|
||||||
|
return _createDependency(token, optional, lowerBoundVisibility, upperBoundVisibility, depProps);
|
||||||
|
} else {
|
||||||
|
throw new NoAnnotationError(typeOrFunc, params);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function _createDependency(token, optional, lowerBoundVisibility, upperBoundVisibility,
|
||||||
|
depProps): ReflectiveDependency {
|
||||||
|
return new ReflectiveDependency(ReflectiveKey.get(token), optional, lowerBoundVisibility,
|
||||||
|
upperBoundVisibility, depProps);
|
||||||
|
}
|
@ -1,4 +1,9 @@
|
|||||||
import {Key, Injector, ResolvedProvider, Provider, provide, Injectable} from 'angular2/src/core/di';
|
import {
|
||||||
|
Injector,
|
||||||
|
ResolvedReflectiveProvider,
|
||||||
|
Injectable,
|
||||||
|
ReflectiveInjector
|
||||||
|
} from 'angular2/src/core/di';
|
||||||
import {ComponentResolver} from './component_resolver';
|
import {ComponentResolver} from './component_resolver';
|
||||||
import {isType, Type, stringify, isPresent} from 'angular2/src/facade/lang';
|
import {isType, Type, stringify, isPresent} from 'angular2/src/facade/lang';
|
||||||
import {ComponentRef} from './component_factory';
|
import {ComponentRef} from './component_factory';
|
||||||
@ -60,6 +65,7 @@ export abstract class DynamicComponentLoader {
|
|||||||
abstract loadAsRoot(type: Type, overrideSelectorOrNode: string | any, injector: Injector,
|
abstract loadAsRoot(type: Type, overrideSelectorOrNode: string | any, injector: Injector,
|
||||||
onDispose?: () => void, projectableNodes?: any[][]): Promise<ComponentRef>;
|
onDispose?: () => void, projectableNodes?: any[][]): Promise<ComponentRef>;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates an instance of a Component and attaches it to the View Container found at the
|
* Creates an instance of a Component and attaches it to the View Container found at the
|
||||||
* `location` specified as {@link ViewContainerRef}.
|
* `location` specified as {@link ViewContainerRef}.
|
||||||
@ -101,7 +107,7 @@ export abstract class DynamicComponentLoader {
|
|||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
abstract loadNextToLocation(type: Type, location: ViewContainerRef,
|
abstract loadNextToLocation(type: Type, location: ViewContainerRef,
|
||||||
providers?: ResolvedProvider[],
|
providers?: ResolvedReflectiveProvider[],
|
||||||
projectableNodes?: any[][]): Promise<ComponentRef>;
|
projectableNodes?: any[][]): Promise<ComponentRef>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -122,10 +128,15 @@ export class DynamicComponentLoader_ extends DynamicComponentLoader {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
loadNextToLocation(type: Type, location: ViewContainerRef, providers: ResolvedProvider[] = null,
|
loadNextToLocation(type: Type, location: ViewContainerRef,
|
||||||
|
providers: ResolvedReflectiveProvider[] = null,
|
||||||
projectableNodes: any[][] = null): Promise<ComponentRef> {
|
projectableNodes: any[][] = null): Promise<ComponentRef> {
|
||||||
return this._compiler.resolveComponent(type).then(componentFactory => {
|
return this._compiler.resolveComponent(type).then(componentFactory => {
|
||||||
return location.createComponent(componentFactory, location.length, providers,
|
var contextInjector = location.parentInjector;
|
||||||
|
var childInjector = isPresent(providers) && providers.length > 0 ?
|
||||||
|
ReflectiveInjector.fromResolvedProviders(providers, contextInjector) :
|
||||||
|
contextInjector;
|
||||||
|
return location.createComponent(componentFactory, location.length, childInjector,
|
||||||
projectableNodes);
|
projectableNodes);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -1,22 +1,19 @@
|
|||||||
import {isBlank, stringify} from 'angular2/src/facade/lang';
|
import {isBlank, stringify, CONST_EXPR} from 'angular2/src/facade/lang';
|
||||||
import {Injector, UNDEFINED} from 'angular2/src/core/di/injector';
|
import {Injector, THROW_IF_NOT_FOUND} from 'angular2/src/core/di/injector';
|
||||||
import {AppView} from './view';
|
import {AppView} from './view';
|
||||||
|
|
||||||
|
const _UNDEFINED = CONST_EXPR(new Object());
|
||||||
|
|
||||||
export class ElementInjector extends Injector {
|
export class ElementInjector extends Injector {
|
||||||
constructor(private _view: AppView<any>, private _nodeIndex: number) { super(); }
|
constructor(private _view: AppView<any>, private _nodeIndex: number) { super(); }
|
||||||
|
|
||||||
get(token: any): any {
|
get(token: any, notFoundValue: any = THROW_IF_NOT_FOUND): any {
|
||||||
var result = this._view.injectorGet(token, this._nodeIndex, UNDEFINED);
|
var result = _UNDEFINED;
|
||||||
if (result === UNDEFINED) {
|
if (result === _UNDEFINED) {
|
||||||
result = this._view.parentInjector.get(token);
|
result = this._view.injectorGet(token, this._nodeIndex, _UNDEFINED);
|
||||||
}
|
}
|
||||||
return result;
|
if (result === _UNDEFINED) {
|
||||||
}
|
result = this._view.parentInjector.get(token, notFoundValue);
|
||||||
|
|
||||||
getOptional(token: any): any {
|
|
||||||
var result = this._view.injectorGet(token, this._nodeIndex, UNDEFINED);
|
|
||||||
if (result === UNDEFINED) {
|
|
||||||
result = this._view.parentInjector.getOptional(token);
|
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,8 @@
|
|||||||
import {ListWrapper} from 'angular2/src/facade/collection';
|
import {ListWrapper} from 'angular2/src/facade/collection';
|
||||||
import {unimplemented} from 'angular2/src/facade/exceptions';
|
import {unimplemented} from 'angular2/src/facade/exceptions';
|
||||||
import {Injector, Injector_, ProtoInjector} from 'angular2/src/core/di/injector';
|
import {Injector} from 'angular2/src/core/di/injector';
|
||||||
import {ResolvedProvider} from 'angular2/src/core/di/provider';
|
import {ReflectiveInjector} from 'angular2/src/core/di/reflective_injector';
|
||||||
|
import {ResolvedReflectiveProvider} from 'angular2/src/core/di/reflective_provider';
|
||||||
import {isPresent, isBlank} from 'angular2/src/facade/lang';
|
import {isPresent, isBlank} from 'angular2/src/facade/lang';
|
||||||
import {wtfCreateScope, wtfLeave, WtfScopeFn} from '../profile/profile';
|
import {wtfCreateScope, wtfLeave, WtfScopeFn} from '../profile/profile';
|
||||||
|
|
||||||
@ -36,6 +37,10 @@ export abstract class ViewContainerRef {
|
|||||||
*/
|
*/
|
||||||
get element(): ElementRef { return <ElementRef>unimplemented(); }
|
get element(): ElementRef { return <ElementRef>unimplemented(); }
|
||||||
|
|
||||||
|
get injector(): Injector { return <Injector>unimplemented(); }
|
||||||
|
|
||||||
|
get parentInjector(): Injector { return <Injector>unimplemented(); }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Destroys all Views in this container.
|
* Destroys all Views in this container.
|
||||||
*/
|
*/
|
||||||
@ -65,18 +70,17 @@ export abstract class ViewContainerRef {
|
|||||||
* Instantiates a single {@link Component} and inserts its Host View into this container at the
|
* Instantiates a single {@link Component} and inserts its Host View into this container at the
|
||||||
* specified `index`.
|
* specified `index`.
|
||||||
*
|
*
|
||||||
* The component is instantiated using its {@link ProtoViewRef `protoView`} which can be
|
* The component is instantiated using its {@link ComponentFactory} which can be
|
||||||
* obtained via {@link Compiler#compileInHost}.
|
* obtained via {@link ComponentResolver#resolveComponent}.
|
||||||
*
|
*
|
||||||
* If `index` is not specified, the new View will be inserted as the last View in the container.
|
* If `index` is not specified, the new View will be inserted as the last View in the container.
|
||||||
*
|
*
|
||||||
* You can optionally specify `dynamicallyCreatedProviders`, which configure the {@link Injector}
|
* You can optionally specify the {@link Injector}
|
||||||
* that will be created for the Host View.
|
* that will be used for the component.
|
||||||
*
|
*
|
||||||
* Returns the {@link ComponentRef} of the Host View created for the newly instantiated Component.
|
* Returns the {@link ComponentRef} of the Host View created for the newly instantiated Component.
|
||||||
*/
|
*/
|
||||||
abstract createComponent(componentFactory: ComponentFactory, index?: number,
|
abstract createComponent(componentFactory: ComponentFactory, index?: number, injector?: Injector,
|
||||||
dynamicallyCreatedProviders?: ResolvedProvider[],
|
|
||||||
projectableNodes?: any[][]): ComponentRef;
|
projectableNodes?: any[][]): ComponentRef;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -120,6 +124,10 @@ export class ViewContainerRef_ implements ViewContainerRef {
|
|||||||
|
|
||||||
get element(): ElementRef { return this._element.elementRef; }
|
get element(): ElementRef { return this._element.elementRef; }
|
||||||
|
|
||||||
|
get injector(): Injector { return this._element.injector; }
|
||||||
|
|
||||||
|
get parentInjector(): Injector { return this._element.parentInjector; }
|
||||||
|
|
||||||
// TODO(rado): profile and decide whether bounds checks should be added
|
// TODO(rado): profile and decide whether bounds checks should be added
|
||||||
// to the methods below.
|
// to the methods below.
|
||||||
createEmbeddedView(templateRef: TemplateRef, index: number = -1): EmbeddedViewRef {
|
createEmbeddedView(templateRef: TemplateRef, index: number = -1): EmbeddedViewRef {
|
||||||
@ -132,18 +140,11 @@ export class ViewContainerRef_ implements ViewContainerRef {
|
|||||||
_createComponentInContainerScope: WtfScopeFn =
|
_createComponentInContainerScope: WtfScopeFn =
|
||||||
wtfCreateScope('ViewContainerRef#createComponent()');
|
wtfCreateScope('ViewContainerRef#createComponent()');
|
||||||
|
|
||||||
createComponent(componentFactory: ComponentFactory, index: number = -1,
|
createComponent(componentFactory: ComponentFactory, index: number = -1, injector: Injector = null,
|
||||||
dynamicallyCreatedProviders: ResolvedProvider[] = null,
|
|
||||||
projectableNodes: any[][] = null): ComponentRef {
|
projectableNodes: any[][] = null): ComponentRef {
|
||||||
var s = this._createComponentInContainerScope();
|
var s = this._createComponentInContainerScope();
|
||||||
var contextInjector = this._element.parentInjector;
|
var contextInjector = isPresent(injector) ? injector : this._element.parentInjector;
|
||||||
|
var componentRef = componentFactory.create(contextInjector, projectableNodes);
|
||||||
var childInjector =
|
|
||||||
isPresent(dynamicallyCreatedProviders) && dynamicallyCreatedProviders.length > 0 ?
|
|
||||||
new Injector_(ProtoInjector.fromResolvedProviders(dynamicallyCreatedProviders),
|
|
||||||
contextInjector) :
|
|
||||||
contextInjector;
|
|
||||||
var componentRef = componentFactory.create(childInjector, projectableNodes);
|
|
||||||
this.insert(componentRef.hostView, index);
|
this.insert(componentRef.hostView, index);
|
||||||
return wtfLeave(s, componentRef);
|
return wtfLeave(s, componentRef);
|
||||||
}
|
}
|
||||||
|
@ -8,9 +8,8 @@ import {
|
|||||||
DynamicComponentLoader,
|
DynamicComponentLoader,
|
||||||
ComponentRef,
|
ComponentRef,
|
||||||
ViewContainerRef,
|
ViewContainerRef,
|
||||||
Injector,
|
|
||||||
provide,
|
provide,
|
||||||
Dependency,
|
ReflectiveInjector,
|
||||||
OnDestroy,
|
OnDestroy,
|
||||||
Output
|
Output
|
||||||
} from 'angular2/core';
|
} from 'angular2/core';
|
||||||
@ -60,7 +59,7 @@ export class RouterOutlet implements OnDestroy {
|
|||||||
var componentType = nextInstruction.componentType;
|
var componentType = nextInstruction.componentType;
|
||||||
var childRouter = this._parentRouter.childRouter(componentType);
|
var childRouter = this._parentRouter.childRouter(componentType);
|
||||||
|
|
||||||
var providers = Injector.resolve([
|
var providers = ReflectiveInjector.resolve([
|
||||||
provide(RouteData, {useValue: nextInstruction.routeData}),
|
provide(RouteData, {useValue: nextInstruction.routeData}),
|
||||||
provide(RouteParams, {useValue: new RouteParams(nextInstruction.params)}),
|
provide(RouteParams, {useValue: new RouteParams(nextInstruction.params)}),
|
||||||
provide(routerMod.Router, {useValue: childRouter})
|
provide(routerMod.Router, {useValue: childRouter})
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import {Injector, Provider, PLATFORM_INITIALIZER} from 'angular2/core';
|
import {ReflectiveInjector, Provider, PLATFORM_INITIALIZER} from 'angular2/core';
|
||||||
import {BaseException, ExceptionHandler} from 'angular2/src/facade/exceptions';
|
import {BaseException, ExceptionHandler} from 'angular2/src/facade/exceptions';
|
||||||
import {ListWrapper} from 'angular2/src/facade/collection';
|
import {ListWrapper} from 'angular2/src/facade/collection';
|
||||||
import {FunctionWrapper, isPresent, Type} from 'angular2/src/facade/lang';
|
import {FunctionWrapper, isPresent, Type} from 'angular2/src/facade/lang';
|
||||||
@ -6,7 +6,7 @@ import {FunctionWrapper, isPresent, Type} from 'angular2/src/facade/lang';
|
|||||||
export class TestInjector {
|
export class TestInjector {
|
||||||
private _instantiated: boolean = false;
|
private _instantiated: boolean = false;
|
||||||
|
|
||||||
private _injector: Injector = null;
|
private _injector: ReflectiveInjector = null;
|
||||||
|
|
||||||
private _providers: Array<Type | Provider | any[]> = [];
|
private _providers: Array<Type | Provider | any[]> = [];
|
||||||
|
|
||||||
@ -28,7 +28,7 @@ export class TestInjector {
|
|||||||
}
|
}
|
||||||
|
|
||||||
createInjector() {
|
createInjector() {
|
||||||
var rootInjector = Injector.resolveAndCreate(this.platformProviders);
|
var rootInjector = ReflectiveInjector.resolveAndCreate(this.platformProviders);
|
||||||
this._injector = rootInjector.resolveAndCreateChild(
|
this._injector = rootInjector.resolveAndCreateChild(
|
||||||
ListWrapper.concat(this.applicationProviders, this._providers));
|
ListWrapper.concat(this.applicationProviders, this._providers));
|
||||||
this._instantiated = true;
|
this._instantiated = true;
|
||||||
@ -76,7 +76,7 @@ export function setBaseTestProviders(platformProviders: Array<Type | Provider |
|
|||||||
testInjector.platformProviders = platformProviders;
|
testInjector.platformProviders = platformProviders;
|
||||||
testInjector.applicationProviders = applicationProviders;
|
testInjector.applicationProviders = applicationProviders;
|
||||||
var injector = testInjector.createInjector();
|
var injector = testInjector.createInjector();
|
||||||
let inits: Function[] = injector.getOptional(PLATFORM_INITIALIZER);
|
let inits: Function[] = injector.get(PLATFORM_INITIALIZER, null);
|
||||||
if (isPresent(inits)) {
|
if (isPresent(inits)) {
|
||||||
inits.forEach(init => init());
|
inits.forEach(init => init());
|
||||||
}
|
}
|
||||||
@ -201,7 +201,7 @@ export class FunctionWithParamTokens {
|
|||||||
/**
|
/**
|
||||||
* Returns the value of the executed function.
|
* Returns the value of the executed function.
|
||||||
*/
|
*/
|
||||||
execute(injector: Injector): any {
|
execute(injector: ReflectiveInjector): any {
|
||||||
var params = this._tokens.map(t => injector.get(t));
|
var params = this._tokens.map(t => injector.get(t));
|
||||||
return FunctionWrapper.apply(this._fn, params);
|
return FunctionWrapper.apply(this._fn, params);
|
||||||
}
|
}
|
||||||
|
@ -5,7 +5,8 @@ import {
|
|||||||
OnChanges,
|
OnChanges,
|
||||||
ComponentFactory,
|
ComponentFactory,
|
||||||
ComponentRef,
|
ComponentRef,
|
||||||
SimpleChange
|
SimpleChange,
|
||||||
|
ReflectiveInjector
|
||||||
} from 'angular2/core';
|
} from 'angular2/core';
|
||||||
import {NG1_SCOPE} from './constants';
|
import {NG1_SCOPE} from './constants';
|
||||||
import {ComponentInfo} from './metadata';
|
import {ComponentInfo} from './metadata';
|
||||||
@ -36,8 +37,8 @@ export class DowngradeNg2ComponentAdapter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bootstrapNg2() {
|
bootstrapNg2() {
|
||||||
var childInjector = this.parentInjector.resolveAndCreateChild(
|
var childInjector = ReflectiveInjector.resolveAndCreate(
|
||||||
[provide(NG1_SCOPE, {useValue: this.componentScope})]);
|
[provide(NG1_SCOPE, {useValue: this.componentScope})], this.parentInjector);
|
||||||
this.contentInsertionPoint = document.createComment('ng1 insertion point');
|
this.contentInsertionPoint = document.createComment('ng1 insertion point');
|
||||||
|
|
||||||
this.componentRef =
|
this.componentRef =
|
||||||
|
@ -10,7 +10,7 @@ import {
|
|||||||
} from 'angular2/testing_internal';
|
} from 'angular2/testing_internal';
|
||||||
import {SpyIterableDifferFactory} from '../../spies';
|
import {SpyIterableDifferFactory} from '../../spies';
|
||||||
import {IterableDiffers} from 'angular2/src/core/change_detection/differs/iterable_differs';
|
import {IterableDiffers} from 'angular2/src/core/change_detection/differs/iterable_differs';
|
||||||
import {Injector, provide} from 'angular2/core';
|
import {Injector, provide, ReflectiveInjector} from 'angular2/core';
|
||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
describe('IterableDiffers', function() {
|
describe('IterableDiffers', function() {
|
||||||
@ -51,7 +51,7 @@ export function main() {
|
|||||||
|
|
||||||
describe(".extend()", () => {
|
describe(".extend()", () => {
|
||||||
it('should throw if calling extend when creating root injector', () => {
|
it('should throw if calling extend when creating root injector', () => {
|
||||||
var injector = Injector.resolveAndCreate([IterableDiffers.extend([])]);
|
var injector = ReflectiveInjector.resolveAndCreate([IterableDiffers.extend([])]);
|
||||||
|
|
||||||
expect(() => injector.get(IterableDiffers))
|
expect(() => injector.get(IterableDiffers))
|
||||||
.toThrowErrorWith("Cannot extend IterableDiffers without a parent injector");
|
.toThrowErrorWith("Cannot extend IterableDiffers without a parent injector");
|
||||||
@ -59,7 +59,8 @@ export function main() {
|
|||||||
|
|
||||||
it('should extend di-inherited diffesr', () => {
|
it('should extend di-inherited diffesr', () => {
|
||||||
var parent = new IterableDiffers([factory1]);
|
var parent = new IterableDiffers([factory1]);
|
||||||
var injector = Injector.resolveAndCreate([provide(IterableDiffers, {useValue: parent})]);
|
var injector =
|
||||||
|
ReflectiveInjector.resolveAndCreate([provide(IterableDiffers, {useValue: parent})]);
|
||||||
var childInjector = injector.resolveAndCreateChild([IterableDiffers.extend([factory2])]);
|
var childInjector = injector.resolveAndCreateChild([IterableDiffers.extend([factory2])]);
|
||||||
|
|
||||||
expect(injector.get(IterableDiffers).factories).toEqual([factory1]);
|
expect(injector.get(IterableDiffers).factories).toEqual([factory1]);
|
||||||
|
@ -2,10 +2,10 @@ import {isBlank, stringify, isPresent} from 'angular2/src/facade/lang';
|
|||||||
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
|
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
|
||||||
import {describe, ddescribe, it, iit, expect, beforeEach} from 'angular2/testing_internal';
|
import {describe, ddescribe, it, iit, expect, beforeEach} from 'angular2/testing_internal';
|
||||||
import {
|
import {
|
||||||
Injector,
|
|
||||||
provide,
|
provide,
|
||||||
ResolvedProvider,
|
ReflectiveKey,
|
||||||
Key,
|
ReflectiveInjector,
|
||||||
|
Injector,
|
||||||
forwardRef,
|
forwardRef,
|
||||||
Injectable,
|
Injectable,
|
||||||
InjectMetadata,
|
InjectMetadata,
|
||||||
@ -15,15 +15,14 @@ import {
|
|||||||
Inject,
|
Inject,
|
||||||
Provider
|
Provider
|
||||||
} from 'angular2/core';
|
} from 'angular2/core';
|
||||||
import {Injector_} from 'angular2/src/core/di/injector';
|
|
||||||
import {DependencyMetadata} from 'angular2/src/core/di/metadata';
|
|
||||||
import {ResolvedProvider_} from 'angular2/src/core/di/provider';
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
InjectorInlineStrategy,
|
ReflectiveInjector_,
|
||||||
InjectorDynamicStrategy,
|
ReflectiveInjectorInlineStrategy,
|
||||||
ProtoInjector
|
ReflectiveInjectorDynamicStrategy,
|
||||||
} from 'angular2/src/core/di/injector';
|
ReflectiveProtoInjector
|
||||||
|
} from 'angular2/src/core/di/reflective_injector';
|
||||||
|
import {DependencyMetadata} from 'angular2/src/core/di/metadata';
|
||||||
|
import {ResolvedReflectiveProvider_} from 'angular2/src/core/di/reflective_provider';
|
||||||
|
|
||||||
class CustomDependencyMetadata extends DependencyMetadata {}
|
class CustomDependencyMetadata extends DependencyMetadata {}
|
||||||
|
|
||||||
@ -102,18 +101,19 @@ export function main() {
|
|||||||
provide('provider10', {useValue: 1})
|
provide('provider10', {useValue: 1})
|
||||||
];
|
];
|
||||||
|
|
||||||
[{strategy: 'inline', providers: [], strategyClass: InjectorInlineStrategy},
|
[{strategy: 'inline', providers: [], strategyClass: ReflectiveInjectorInlineStrategy},
|
||||||
{
|
{
|
||||||
strategy: 'dynamic',
|
strategy: 'dynamic',
|
||||||
providers: dynamicProviders,
|
providers: dynamicProviders,
|
||||||
strategyClass: InjectorDynamicStrategy
|
strategyClass: ReflectiveInjectorDynamicStrategy
|
||||||
}].forEach((context) => {
|
}].forEach((context) => {
|
||||||
function createInjector(providers: any[], parent: Injector = null): Injector_ {
|
function createInjector(providers: any[],
|
||||||
var resolvedProviders = Injector.resolve(providers.concat(context['providers']));
|
parent: ReflectiveInjector = null): ReflectiveInjector_ {
|
||||||
|
var resolvedProviders = ReflectiveInjector.resolve(providers.concat(context['providers']));
|
||||||
if (isPresent(parent)) {
|
if (isPresent(parent)) {
|
||||||
return <Injector_>parent.createChildFromResolved(resolvedProviders);
|
return <ReflectiveInjector_>parent.createChildFromResolved(resolvedProviders);
|
||||||
} else {
|
} else {
|
||||||
return <Injector_>Injector.fromResolvedProviders(resolvedProviders);
|
return <ReflectiveInjector_>ReflectiveInjector.fromResolvedProviders(resolvedProviders);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -357,9 +357,10 @@ export function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should show the full path when error happens in a constructor', () => {
|
it('should show the full path when error happens in a constructor', () => {
|
||||||
var providers = Injector.resolve([Car, provide(Engine, {useClass: BrokenEngine})]);
|
var providers =
|
||||||
var proto = new ProtoInjector([providers[0], providers[1]]);
|
ReflectiveInjector.resolve([Car, provide(Engine, {useClass: BrokenEngine})]);
|
||||||
var injector = new Injector_(proto);
|
var proto = new ReflectiveProtoInjector([providers[0], providers[1]]);
|
||||||
|
var injector = new ReflectiveInjector_(proto);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
injector.get(Car);
|
injector.get(Car);
|
||||||
@ -373,14 +374,15 @@ export function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should provide context when throwing an exception ', () => {
|
it('should provide context when throwing an exception ', () => {
|
||||||
var engineProvider = Injector.resolve([provide(Engine, {useClass: BrokenEngine})])[0];
|
var engineProvider =
|
||||||
var protoParent = new ProtoInjector([engineProvider]);
|
ReflectiveInjector.resolve([provide(Engine, {useClass: BrokenEngine})])[0];
|
||||||
|
var protoParent = new ReflectiveProtoInjector([engineProvider]);
|
||||||
|
|
||||||
var carProvider = Injector.resolve([Car])[0];
|
var carProvider = ReflectiveInjector.resolve([Car])[0];
|
||||||
var protoChild = new ProtoInjector([carProvider]);
|
var protoChild = new ReflectiveProtoInjector([carProvider]);
|
||||||
|
|
||||||
var parent = new Injector_(protoParent, null, () => "parentContext");
|
var parent = new ReflectiveInjector_(protoParent, null, () => "parentContext");
|
||||||
var child = new Injector_(protoChild, parent, () => "childContext");
|
var child = new ReflectiveInjector_(protoChild, parent, () => "childContext");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
child.get(Car);
|
child.get(Car);
|
||||||
@ -415,7 +417,7 @@ export function main() {
|
|||||||
|
|
||||||
describe("child", () => {
|
describe("child", () => {
|
||||||
it('should load instances from parent injector', () => {
|
it('should load instances from parent injector', () => {
|
||||||
var parent = Injector.resolveAndCreate([Engine]);
|
var parent = ReflectiveInjector.resolveAndCreate([Engine]);
|
||||||
var child = parent.resolveAndCreateChild([]);
|
var child = parent.resolveAndCreateChild([]);
|
||||||
|
|
||||||
var engineFromParent = parent.get(Engine);
|
var engineFromParent = parent.get(Engine);
|
||||||
@ -426,7 +428,7 @@ export function main() {
|
|||||||
|
|
||||||
it("should not use the child providers when resolving the dependencies of a parent provider",
|
it("should not use the child providers when resolving the dependencies of a parent provider",
|
||||||
() => {
|
() => {
|
||||||
var parent = Injector.resolveAndCreate([Car, Engine]);
|
var parent = ReflectiveInjector.resolveAndCreate([Car, Engine]);
|
||||||
var child = parent.resolveAndCreateChild([provide(Engine, {useClass: TurboEngine})]);
|
var child = parent.resolveAndCreateChild([provide(Engine, {useClass: TurboEngine})]);
|
||||||
|
|
||||||
var carFromChild = child.get(Car);
|
var carFromChild = child.get(Car);
|
||||||
@ -434,7 +436,7 @@ export function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should create new instance in a child injector', () => {
|
it('should create new instance in a child injector', () => {
|
||||||
var parent = Injector.resolveAndCreate([Engine]);
|
var parent = ReflectiveInjector.resolveAndCreate([Engine]);
|
||||||
var child = parent.resolveAndCreateChild([provide(Engine, {useClass: TurboEngine})]);
|
var child = parent.resolveAndCreateChild([provide(Engine, {useClass: TurboEngine})]);
|
||||||
|
|
||||||
var engineFromParent = parent.get(Engine);
|
var engineFromParent = parent.get(Engine);
|
||||||
@ -445,7 +447,7 @@ export function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should give access to parent", () => {
|
it("should give access to parent", () => {
|
||||||
var parent = Injector.resolveAndCreate([]);
|
var parent = ReflectiveInjector.resolveAndCreate([]);
|
||||||
var child = parent.resolveAndCreateChild([]);
|
var child = parent.resolveAndCreateChild([]);
|
||||||
expect(child.parent).toBe(parent);
|
expect(child.parent).toBe(parent);
|
||||||
});
|
});
|
||||||
@ -453,14 +455,14 @@ export function main() {
|
|||||||
|
|
||||||
describe('resolveAndInstantiate', () => {
|
describe('resolveAndInstantiate', () => {
|
||||||
it('should instantiate an object in the context of the injector', () => {
|
it('should instantiate an object in the context of the injector', () => {
|
||||||
var inj = Injector.resolveAndCreate([Engine]);
|
var inj = ReflectiveInjector.resolveAndCreate([Engine]);
|
||||||
var car = inj.resolveAndInstantiate(Car);
|
var car = inj.resolveAndInstantiate(Car);
|
||||||
expect(car).toBeAnInstanceOf(Car);
|
expect(car).toBeAnInstanceOf(Car);
|
||||||
expect(car.engine).toBe(inj.get(Engine));
|
expect(car.engine).toBe(inj.get(Engine));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not store the instantiated object in the injector', () => {
|
it('should not store the instantiated object in the injector', () => {
|
||||||
var inj = Injector.resolveAndCreate([Engine]);
|
var inj = ReflectiveInjector.resolveAndCreate([Engine]);
|
||||||
inj.resolveAndInstantiate(Car);
|
inj.resolveAndInstantiate(Car);
|
||||||
expect(() => inj.get(Car)).toThrowError();
|
expect(() => inj.get(Car)).toThrowError();
|
||||||
});
|
});
|
||||||
@ -468,8 +470,8 @@ export function main() {
|
|||||||
|
|
||||||
describe('instantiate', () => {
|
describe('instantiate', () => {
|
||||||
it('should instantiate an object in the context of the injector', () => {
|
it('should instantiate an object in the context of the injector', () => {
|
||||||
var inj = Injector.resolveAndCreate([Engine]);
|
var inj = ReflectiveInjector.resolveAndCreate([Engine]);
|
||||||
var car = inj.instantiateResolved(Injector.resolve([Car])[0]);
|
var car = inj.instantiateResolved(ReflectiveInjector.resolve([Car])[0]);
|
||||||
expect(car).toBeAnInstanceOf(Car);
|
expect(car).toBeAnInstanceOf(Car);
|
||||||
expect(car.engine).toBe(inj.get(Engine));
|
expect(car.engine).toBe(inj.get(Engine));
|
||||||
});
|
});
|
||||||
@ -478,7 +480,7 @@ export function main() {
|
|||||||
describe("depedency resolution", () => {
|
describe("depedency resolution", () => {
|
||||||
describe("@Self()", () => {
|
describe("@Self()", () => {
|
||||||
it("should return a dependency from self", () => {
|
it("should return a dependency from self", () => {
|
||||||
var inj = Injector.resolveAndCreate([
|
var inj = ReflectiveInjector.resolveAndCreate([
|
||||||
Engine,
|
Engine,
|
||||||
provide(Car, {useFactory: (e) => new Car(e), deps: [[Engine, new SelfMetadata()]]})
|
provide(Car, {useFactory: (e) => new Car(e), deps: [[Engine, new SelfMetadata()]]})
|
||||||
]);
|
]);
|
||||||
@ -487,7 +489,7 @@ export function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should throw when not requested provider on self", () => {
|
it("should throw when not requested provider on self", () => {
|
||||||
var parent = Injector.resolveAndCreate([Engine]);
|
var parent = ReflectiveInjector.resolveAndCreate([Engine]);
|
||||||
var child = parent.resolveAndCreateChild([
|
var child = parent.resolveAndCreateChild([
|
||||||
provide(Car, {useFactory: (e) => new Car(e), deps: [[Engine, new SelfMetadata()]]})
|
provide(Car, {useFactory: (e) => new Car(e), deps: [[Engine, new SelfMetadata()]]})
|
||||||
]);
|
]);
|
||||||
@ -499,7 +501,7 @@ export function main() {
|
|||||||
|
|
||||||
describe("default", () => {
|
describe("default", () => {
|
||||||
it("should not skip self", () => {
|
it("should not skip self", () => {
|
||||||
var parent = Injector.resolveAndCreate([Engine]);
|
var parent = ReflectiveInjector.resolveAndCreate([Engine]);
|
||||||
var child = parent.resolveAndCreateChild([
|
var child = parent.resolveAndCreateChild([
|
||||||
provide(Engine, {useClass: TurboEngine}),
|
provide(Engine, {useClass: TurboEngine}),
|
||||||
provide(Car, {useFactory: (e) => new Car(e), deps: [Engine]})
|
provide(Car, {useFactory: (e) => new Car(e), deps: [Engine]})
|
||||||
@ -512,15 +514,15 @@ export function main() {
|
|||||||
|
|
||||||
describe('resolve', () => {
|
describe('resolve', () => {
|
||||||
it('should resolve and flatten', () => {
|
it('should resolve and flatten', () => {
|
||||||
var providers = Injector.resolve([Engine, [BrokenEngine]]);
|
var providers = ReflectiveInjector.resolve([Engine, [BrokenEngine]]);
|
||||||
providers.forEach(function(b) {
|
providers.forEach(function(b) {
|
||||||
if (isBlank(b)) return; // the result is a sparse array
|
if (isBlank(b)) return; // the result is a sparse array
|
||||||
expect(b instanceof ResolvedProvider_).toBe(true);
|
expect(b instanceof ResolvedReflectiveProvider_).toBe(true);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should support multi providers", () => {
|
it("should support multi providers", () => {
|
||||||
var provider = Injector.resolve([
|
var provider = ReflectiveInjector.resolve([
|
||||||
new Provider(Engine, {useClass: BrokenEngine, multi: true}),
|
new Provider(Engine, {useClass: BrokenEngine, multi: true}),
|
||||||
new Provider(Engine, {useClass: TurboEngine, multi: true})
|
new Provider(Engine, {useClass: TurboEngine, multi: true})
|
||||||
])[0];
|
])[0];
|
||||||
@ -531,8 +533,8 @@ export function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should support multi providers with only one provider", () => {
|
it("should support multi providers with only one provider", () => {
|
||||||
var provider =
|
var provider = ReflectiveInjector.resolve(
|
||||||
Injector.resolve([new Provider(Engine, {useClass: BrokenEngine, multi: true})])[0];
|
[new Provider(Engine, {useClass: BrokenEngine, multi: true})])[0];
|
||||||
|
|
||||||
expect(provider.key.token).toBe(Engine);
|
expect(provider.key.token).toBe(Engine);
|
||||||
expect(provider.multiProvider).toEqual(true);
|
expect(provider.multiProvider).toEqual(true);
|
||||||
@ -541,16 +543,18 @@ export function main() {
|
|||||||
|
|
||||||
it("should throw when mixing multi providers with regular providers", () => {
|
it("should throw when mixing multi providers with regular providers", () => {
|
||||||
expect(() => {
|
expect(() => {
|
||||||
Injector.resolve([new Provider(Engine, {useClass: BrokenEngine, multi: true}), Engine]);
|
ReflectiveInjector.resolve(
|
||||||
|
[new Provider(Engine, {useClass: BrokenEngine, multi: true}), Engine]);
|
||||||
}).toThrowErrorWith("Cannot mix multi providers and regular providers");
|
}).toThrowErrorWith("Cannot mix multi providers and regular providers");
|
||||||
|
|
||||||
expect(() => {
|
expect(() => {
|
||||||
Injector.resolve([Engine, new Provider(Engine, {useClass: BrokenEngine, multi: true})]);
|
ReflectiveInjector.resolve(
|
||||||
|
[Engine, new Provider(Engine, {useClass: BrokenEngine, multi: true})]);
|
||||||
}).toThrowErrorWith("Cannot mix multi providers and regular providers");
|
}).toThrowErrorWith("Cannot mix multi providers and regular providers");
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should resolve forward references', () => {
|
it('should resolve forward references', () => {
|
||||||
var providers = Injector.resolve([
|
var providers = ReflectiveInjector.resolve([
|
||||||
forwardRef(() => Engine),
|
forwardRef(() => Engine),
|
||||||
[provide(forwardRef(() => BrokenEngine), {useClass: forwardRef(() => Engine)})],
|
[provide(forwardRef(() => BrokenEngine), {useClass: forwardRef(() => Engine)})],
|
||||||
provide(forwardRef(() => String),
|
provide(forwardRef(() => String),
|
||||||
@ -563,11 +567,12 @@ export function main() {
|
|||||||
|
|
||||||
expect(engineProvider.resolvedFactories[0].factory() instanceof Engine).toBe(true);
|
expect(engineProvider.resolvedFactories[0].factory() instanceof Engine).toBe(true);
|
||||||
expect(brokenEngineProvider.resolvedFactories[0].factory() instanceof Engine).toBe(true);
|
expect(brokenEngineProvider.resolvedFactories[0].factory() instanceof Engine).toBe(true);
|
||||||
expect(stringProvider.resolvedFactories[0].dependencies[0].key).toEqual(Key.get(Engine));
|
expect(stringProvider.resolvedFactories[0].dependencies[0].key)
|
||||||
|
.toEqual(ReflectiveKey.get(Engine));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support overriding factory dependencies with dependency annotations', () => {
|
it('should support overriding factory dependencies with dependency annotations', () => {
|
||||||
var providers = Injector.resolve([
|
var providers = ReflectiveInjector.resolve([
|
||||||
provide("token",
|
provide("token",
|
||||||
{
|
{
|
||||||
useFactory: (e) => "result",
|
useFactory: (e) => "result",
|
||||||
@ -583,9 +588,9 @@ export function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should allow declaring dependencies with flat arrays', () => {
|
it('should allow declaring dependencies with flat arrays', () => {
|
||||||
var resolved = Injector.resolve(
|
var resolved = ReflectiveInjector.resolve(
|
||||||
[provide('token', {useFactory: e => e, deps: [new InjectMetadata("dep")]})]);
|
[provide('token', {useFactory: e => e, deps: [new InjectMetadata("dep")]})]);
|
||||||
var nestedResolved = Injector.resolve(
|
var nestedResolved = ReflectiveInjector.resolve(
|
||||||
[provide('token', {useFactory: e => e, deps: [[new InjectMetadata("dep")]]})]);
|
[provide('token', {useFactory: e => e, deps: [[new InjectMetadata("dep")]]})]);
|
||||||
expect(resolved[0].resolvedFactories[0].dependencies[0].key.token)
|
expect(resolved[0].resolvedFactories[0].dependencies[0].key.token)
|
||||||
.toEqual(nestedResolved[0].resolvedFactories[0].dependencies[0].key.token);
|
.toEqual(nestedResolved[0].resolvedFactories[0].dependencies[0].key.token);
|
||||||
@ -594,8 +599,9 @@ export function main() {
|
|||||||
|
|
||||||
describe("displayName", () => {
|
describe("displayName", () => {
|
||||||
it("should work", () => {
|
it("should work", () => {
|
||||||
expect((<Injector_>Injector.resolveAndCreate([Engine, BrokenEngine])).displayName)
|
expect((<ReflectiveInjector_>ReflectiveInjector.resolveAndCreate([Engine, BrokenEngine]))
|
||||||
.toEqual('Injector(providers: [ "Engine" , "BrokenEngine" ])');
|
.displayName)
|
||||||
|
.toEqual('ReflectiveInjector(providers: [ "Engine" , "BrokenEngine" ])');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
@ -1,5 +1,5 @@
|
|||||||
import {describe, iit, it, expect, beforeEach} from 'angular2/testing_internal';
|
import {describe, iit, it, expect, beforeEach} from 'angular2/testing_internal';
|
||||||
import {Key, KeyRegistry} from 'angular2/src/core/di/key';
|
import {ReflectiveKey, KeyRegistry} from 'angular2/src/core/di/reflective_key';
|
||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
describe("key", function() {
|
describe("key", function() {
|
@ -54,7 +54,8 @@ import {
|
|||||||
Host,
|
Host,
|
||||||
SkipSelf,
|
SkipSelf,
|
||||||
SkipSelfMetadata,
|
SkipSelfMetadata,
|
||||||
OnDestroy
|
OnDestroy,
|
||||||
|
ReflectiveInjector
|
||||||
} from 'angular2/core';
|
} from 'angular2/core';
|
||||||
|
|
||||||
import {NgIf, NgFor} from 'angular2/common';
|
import {NgIf, NgFor} from 'angular2/common';
|
||||||
@ -1409,7 +1410,7 @@ function declareTests(isJit: boolean) {
|
|||||||
PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => {
|
PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => {
|
||||||
var c = e.context;
|
var c = e.context;
|
||||||
expect(DOM.nodeName(c.componentRenderElement).toUpperCase()).toEqual("DIV");
|
expect(DOM.nodeName(c.componentRenderElement).toUpperCase()).toEqual("DIV");
|
||||||
expect(c.injector.getOptional).toBeTruthy();
|
expect((<Injector>c.injector).get).toBeTruthy();
|
||||||
async.done();
|
async.done();
|
||||||
return null;
|
return null;
|
||||||
});
|
});
|
||||||
@ -1429,7 +1430,7 @@ function declareTests(isJit: boolean) {
|
|||||||
var c = e.context;
|
var c = e.context;
|
||||||
expect(DOM.nodeName(c.renderNode).toUpperCase()).toEqual("INPUT");
|
expect(DOM.nodeName(c.renderNode).toUpperCase()).toEqual("INPUT");
|
||||||
expect(DOM.nodeName(c.componentRenderElement).toUpperCase()).toEqual("DIV");
|
expect(DOM.nodeName(c.componentRenderElement).toUpperCase()).toEqual("DIV");
|
||||||
expect(c.injector.getOptional).toBeTruthy();
|
expect((<Injector>c.injector).get).toBeTruthy();
|
||||||
expect(c.source).toContain(":0:7");
|
expect(c.source).toContain(":0:7");
|
||||||
expect(c.context).toBe(fixture.debugElement.componentInstance);
|
expect(c.context).toBe(fixture.debugElement.componentInstance);
|
||||||
expect(c.locals["local"]).toBeDefined();
|
expect(c.locals["local"]).toBeDefined();
|
||||||
@ -1485,7 +1486,7 @@ function declareTests(isJit: boolean) {
|
|||||||
var c = e.context;
|
var c = e.context;
|
||||||
expect(DOM.nodeName(c.renderNode).toUpperCase()).toEqual("SPAN");
|
expect(DOM.nodeName(c.renderNode).toUpperCase()).toEqual("SPAN");
|
||||||
expect(DOM.nodeName(c.componentRenderElement).toUpperCase()).toEqual("DIV");
|
expect(DOM.nodeName(c.componentRenderElement).toUpperCase()).toEqual("DIV");
|
||||||
expect(c.injector.getOptional).toBeTruthy();
|
expect((<Injector>c.injector).get).toBeTruthy();
|
||||||
expect(c.context).toBe(fixture.debugElement.componentInstance);
|
expect(c.context).toBe(fixture.debugElement.componentInstance);
|
||||||
expect(c.locals["local"]).toBeDefined();
|
expect(c.locals["local"]).toBeDefined();
|
||||||
}
|
}
|
||||||
@ -1950,9 +1951,10 @@ class DynamicViewport {
|
|||||||
var myService = new MyService();
|
var myService = new MyService();
|
||||||
myService.greeting = 'dynamic greet';
|
myService.greeting = 'dynamic greet';
|
||||||
|
|
||||||
var bindings = Injector.resolve([provide(MyService, {useValue: myService})]);
|
var injector = ReflectiveInjector.resolveAndCreate([provide(MyService, {useValue: myService})],
|
||||||
|
vc.injector);
|
||||||
this.done = compiler.resolveComponent(ChildCompUsingService)
|
this.done = compiler.resolveComponent(ChildCompUsingService)
|
||||||
.then((compFactory) => {vc.createComponent(compFactory, 0, bindings)});
|
.then((componentFactory) => vc.createComponent(componentFactory, 0, injector));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -19,7 +19,7 @@ import {
|
|||||||
JSONPBackend,
|
JSONPBackend,
|
||||||
JSONPBackend_
|
JSONPBackend_
|
||||||
} from 'angular2/src/http/backends/jsonp_backend';
|
} from 'angular2/src/http/backends/jsonp_backend';
|
||||||
import {provide, Injector} from 'angular2/core';
|
import {provide, Injector, ReflectiveInjector} from 'angular2/core';
|
||||||
import {isPresent, StringWrapper} from 'angular2/src/facade/lang';
|
import {isPresent, StringWrapper} from 'angular2/src/facade/lang';
|
||||||
import {TimerWrapper} from 'angular2/src/facade/async';
|
import {TimerWrapper} from 'angular2/src/facade/async';
|
||||||
import {Request} from 'angular2/src/http/static_request';
|
import {Request} from 'angular2/src/http/static_request';
|
||||||
@ -71,7 +71,7 @@ export function main() {
|
|||||||
let sampleRequest: Request;
|
let sampleRequest: Request;
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
let injector = Injector.resolveAndCreate([
|
let injector = ReflectiveInjector.resolveAndCreate([
|
||||||
provide(ResponseOptions, {useClass: BaseResponseOptions}),
|
provide(ResponseOptions, {useClass: BaseResponseOptions}),
|
||||||
provide(BrowserJsonp, {useClass: MockBrowserJsonp}),
|
provide(BrowserJsonp, {useClass: MockBrowserJsonp}),
|
||||||
provide(JSONPBackend, {useClass: JSONPBackend_})
|
provide(JSONPBackend, {useClass: JSONPBackend_})
|
||||||
|
@ -14,7 +14,7 @@ import {
|
|||||||
import {ObservableWrapper} from 'angular2/src/facade/async';
|
import {ObservableWrapper} from 'angular2/src/facade/async';
|
||||||
import {BrowserXhr} from 'angular2/src/http/backends/browser_xhr';
|
import {BrowserXhr} from 'angular2/src/http/backends/browser_xhr';
|
||||||
import {MockConnection, MockBackend} from 'angular2/src/http/backends/mock_backend';
|
import {MockConnection, MockBackend} from 'angular2/src/http/backends/mock_backend';
|
||||||
import {provide, Injector} from 'angular2/core';
|
import {provide, Injector, ReflectiveInjector} from 'angular2/core';
|
||||||
import {Request} from 'angular2/src/http/static_request';
|
import {Request} from 'angular2/src/http/static_request';
|
||||||
import {Response} from 'angular2/src/http/static_response';
|
import {Response} from 'angular2/src/http/static_response';
|
||||||
import {Headers} from 'angular2/src/http/headers';
|
import {Headers} from 'angular2/src/http/headers';
|
||||||
@ -34,7 +34,7 @@ export function main() {
|
|||||||
var sampleResponse2: Response;
|
var sampleResponse2: Response;
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
var injector = Injector.resolveAndCreate(
|
var injector = ReflectiveInjector.resolveAndCreate(
|
||||||
[provide(ResponseOptions, {useClass: BaseResponseOptions}), MockBackend]);
|
[provide(ResponseOptions, {useClass: BaseResponseOptions}), MockBackend]);
|
||||||
backend = injector.get(MockBackend);
|
backend = injector.get(MockBackend);
|
||||||
var base = new BaseRequestOptions();
|
var base = new BaseRequestOptions();
|
||||||
|
@ -14,7 +14,7 @@ import {
|
|||||||
import {ObservableWrapper} from 'angular2/src/facade/async';
|
import {ObservableWrapper} from 'angular2/src/facade/async';
|
||||||
import {BrowserXhr} from 'angular2/src/http/backends/browser_xhr';
|
import {BrowserXhr} from 'angular2/src/http/backends/browser_xhr';
|
||||||
import {XHRConnection, XHRBackend} from 'angular2/src/http/backends/xhr_backend';
|
import {XHRConnection, XHRBackend} from 'angular2/src/http/backends/xhr_backend';
|
||||||
import {provide, Injector} from 'angular2/core';
|
import {provide, Injector, ReflectiveInjector} from 'angular2/core';
|
||||||
import {Request} from 'angular2/src/http/static_request';
|
import {Request} from 'angular2/src/http/static_request';
|
||||||
import {Response} from 'angular2/src/http/static_response';
|
import {Response} from 'angular2/src/http/static_response';
|
||||||
import {Headers} from 'angular2/src/http/headers';
|
import {Headers} from 'angular2/src/http/headers';
|
||||||
@ -86,7 +86,7 @@ export function main() {
|
|||||||
var sampleRequest: Request;
|
var sampleRequest: Request;
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
var injector = Injector.resolveAndCreate([
|
var injector = ReflectiveInjector.resolveAndCreate([
|
||||||
provide(ResponseOptions, {useClass: BaseResponseOptions}),
|
provide(ResponseOptions, {useClass: BaseResponseOptions}),
|
||||||
provide(BrowserXhr, {useClass: MockBrowserXHR}),
|
provide(BrowserXhr, {useClass: MockBrowserXHR}),
|
||||||
XHRBackend
|
XHRBackend
|
||||||
|
@ -10,7 +10,7 @@ import {
|
|||||||
it,
|
it,
|
||||||
xit
|
xit
|
||||||
} from 'angular2/testing_internal';
|
} from 'angular2/testing_internal';
|
||||||
import {Injector, provide} from 'angular2/core';
|
import {Injector, provide, ReflectiveInjector} from 'angular2/core';
|
||||||
import {MockBackend, MockConnection} from 'angular2/src/http/backends/mock_backend';
|
import {MockBackend, MockConnection} from 'angular2/src/http/backends/mock_backend';
|
||||||
import {
|
import {
|
||||||
BaseRequestOptions,
|
BaseRequestOptions,
|
||||||
@ -35,15 +35,15 @@ export function main() {
|
|||||||
describe('injectables', () => {
|
describe('injectables', () => {
|
||||||
var url = 'http://foo.bar';
|
var url = 'http://foo.bar';
|
||||||
var http: Http;
|
var http: Http;
|
||||||
var parentInjector: Injector;
|
var parentInjector: ReflectiveInjector;
|
||||||
var childInjector: Injector;
|
var childInjector: ReflectiveInjector;
|
||||||
var jsonpBackend: MockBackend;
|
var jsonpBackend: MockBackend;
|
||||||
var xhrBackend: MockBackend;
|
var xhrBackend: MockBackend;
|
||||||
var jsonp: Jsonp;
|
var jsonp: Jsonp;
|
||||||
|
|
||||||
it('should allow using jsonpInjectables and httpInjectables in same injector',
|
it('should allow using jsonpInjectables and httpInjectables in same injector',
|
||||||
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
|
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
|
||||||
parentInjector = Injector.resolveAndCreate([
|
parentInjector = ReflectiveInjector.resolveAndCreate([
|
||||||
provide(XHRBackend, {useClass: MockBackend}),
|
provide(XHRBackend, {useClass: MockBackend}),
|
||||||
provide(JSONPBackend, {useClass: MockBackend})
|
provide(JSONPBackend, {useClass: MockBackend})
|
||||||
]);
|
]);
|
||||||
@ -94,7 +94,7 @@ export function main() {
|
|||||||
var baseResponse: Response;
|
var baseResponse: Response;
|
||||||
var jsonp: Jsonp;
|
var jsonp: Jsonp;
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
injector = Injector.resolveAndCreate([
|
injector = ReflectiveInjector.resolveAndCreate([
|
||||||
BaseRequestOptions,
|
BaseRequestOptions,
|
||||||
MockBackend,
|
MockBackend,
|
||||||
provide(
|
provide(
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import 'package:angular2/testing_internal.dart' show SpyObject;
|
import 'package:angular2/testing_internal.dart' show SpyObject;
|
||||||
import 'package:angular2/core.dart' show Injector, bind;
|
import 'package:angular2/core.dart' show Injector, ReflectiveInjector, bind;
|
||||||
import 'package:angular2/src/core/application_ref.dart' show ApplicationRef;
|
import 'package:angular2/src/core/application_ref.dart' show ApplicationRef;
|
||||||
import 'package:angular2/src/core/linker/component_factory.dart'
|
import 'package:angular2/src/core/linker/component_factory.dart'
|
||||||
show ComponentRef;
|
show ComponentRef;
|
||||||
@ -15,7 +15,7 @@ class SpyComponentRef extends SpyObject implements ComponentRef {
|
|||||||
Injector injector;
|
Injector injector;
|
||||||
|
|
||||||
SpyComponentRef() {
|
SpyComponentRef() {
|
||||||
this.injector = Injector
|
this.injector = ReflectiveInjector
|
||||||
.resolveAndCreate([bind(ApplicationRef).toClass(SpyApplicationRef)]);
|
.resolveAndCreate([bind(ApplicationRef).toClass(SpyApplicationRef)]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import {SpyObject} from 'angular2/testing_internal';
|
import {SpyObject} from 'angular2/testing_internal';
|
||||||
import {Injector, provide} from 'angular2/core';
|
import {ReflectiveInjector, provide} from 'angular2/core';
|
||||||
import {global} from 'angular2/src/facade/lang';
|
import {global} from 'angular2/src/facade/lang';
|
||||||
import {ApplicationRef, ApplicationRef_} from 'angular2/src/core/application_ref';
|
import {ApplicationRef, ApplicationRef_} from 'angular2/src/core/application_ref';
|
||||||
|
|
||||||
@ -11,8 +11,8 @@ export class SpyComponentRef extends SpyObject {
|
|||||||
injector;
|
injector;
|
||||||
constructor() {
|
constructor() {
|
||||||
super();
|
super();
|
||||||
this.injector =
|
this.injector = ReflectiveInjector.resolveAndCreate(
|
||||||
Injector.resolveAndCreate([provide(ApplicationRef, {useClass: SpyApplicationRef})]);
|
[provide(ApplicationRef, {useClass: SpyApplicationRef})]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -169,7 +169,7 @@ var NG_CORE = [
|
|||||||
'PLATFORM_PIPES',
|
'PLATFORM_PIPES',
|
||||||
'DebugNode',
|
'DebugNode',
|
||||||
'DebugElement',
|
'DebugElement',
|
||||||
'Dependency',
|
'ReflectiveDependency',
|
||||||
'DependencyMetadata',
|
'DependencyMetadata',
|
||||||
'Directive',
|
'Directive',
|
||||||
'DirectiveMetadata',
|
'DirectiveMetadata',
|
||||||
@ -194,10 +194,11 @@ var NG_CORE = [
|
|||||||
'Injectable',
|
'Injectable',
|
||||||
'InjectableMetadata',
|
'InjectableMetadata',
|
||||||
'Injector',
|
'Injector',
|
||||||
|
'ReflectiveInjector',
|
||||||
'InstantiationError',
|
'InstantiationError',
|
||||||
'InvalidProviderError',
|
'InvalidProviderError',
|
||||||
'IterableDiffers',
|
'IterableDiffers',
|
||||||
'Key',
|
'ReflectiveKey',
|
||||||
'KeyValueChangeRecord',
|
'KeyValueChangeRecord',
|
||||||
'KeyValueDiffers',
|
'KeyValueDiffers',
|
||||||
'NgZone',
|
'NgZone',
|
||||||
@ -219,9 +220,9 @@ var NG_CORE = [
|
|||||||
'Renderer',
|
'Renderer',
|
||||||
'RootRenderer',
|
'RootRenderer',
|
||||||
'RenderComponentType',
|
'RenderComponentType',
|
||||||
'ResolvedBinding:dart',
|
'ResolvedReflectiveBinding:dart',
|
||||||
'ResolvedProvider:dart',
|
'ResolvedReflectiveProvider:dart',
|
||||||
'ResolvedFactory',
|
'ResolvedReflectiveFactory',
|
||||||
'Self',
|
'Self',
|
||||||
'SelfMetadata',
|
'SelfMetadata',
|
||||||
'SkipSelf',
|
'SkipSelf',
|
||||||
|
@ -143,7 +143,8 @@ export class RedirectToParentCmp {
|
|||||||
@RouteConfig([new Route({path: '/', component: HelloCmp})])
|
@RouteConfig([new Route({path: '/', component: HelloCmp})])
|
||||||
export class DynamicLoaderCmp {
|
export class DynamicLoaderCmp {
|
||||||
private _componentRef: ComponentRef = null;
|
private _componentRef: ComponentRef = null;
|
||||||
@ViewChild('viewport', {read: ViewContainerRef}) private _viewport: ViewContainerRef;
|
|
||||||
|
@ViewChild('viewport', {read: ViewContainerRef}) viewport: ViewContainerRef;
|
||||||
|
|
||||||
constructor(private _dynamicComponentLoader: DynamicComponentLoader) {}
|
constructor(private _dynamicComponentLoader: DynamicComponentLoader) {}
|
||||||
|
|
||||||
@ -152,8 +153,7 @@ export class DynamicLoaderCmp {
|
|||||||
this._componentRef.destroy();
|
this._componentRef.destroy();
|
||||||
this._componentRef = null;
|
this._componentRef = null;
|
||||||
}
|
}
|
||||||
return this._dynamicComponentLoader.loadNextToLocation(DynamicallyLoadedComponent,
|
return this._dynamicComponentLoader.loadNextToLocation(DynamicallyLoadedComponent, viewport)
|
||||||
this._viewport)
|
|
||||||
.then((cmp) => { this._componentRef = cmp; });
|
.then((cmp) => { this._componentRef = cmp; });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -12,7 +12,7 @@ import {
|
|||||||
SpyObject
|
SpyObject
|
||||||
} from 'angular2/testing_internal';
|
} from 'angular2/testing_internal';
|
||||||
|
|
||||||
import {Injector, provide} from 'angular2/core';
|
import {Injector, provide, ReflectiveInjector} from 'angular2/core';
|
||||||
import {CONST_EXPR} from 'angular2/src/facade/lang';
|
import {CONST_EXPR} from 'angular2/src/facade/lang';
|
||||||
|
|
||||||
import {Location, LocationStrategy, APP_BASE_HREF} from 'angular2/platform/common';
|
import {Location, LocationStrategy, APP_BASE_HREF} from 'angular2/platform/common';
|
||||||
@ -26,7 +26,7 @@ export function main() {
|
|||||||
function makeLocation(baseHref: string = '/my/app', provider: any = CONST_EXPR([])): Location {
|
function makeLocation(baseHref: string = '/my/app', provider: any = CONST_EXPR([])): Location {
|
||||||
locationStrategy = new MockLocationStrategy();
|
locationStrategy = new MockLocationStrategy();
|
||||||
locationStrategy.internalBaseHref = baseHref;
|
locationStrategy.internalBaseHref = baseHref;
|
||||||
let injector = Injector.resolveAndCreate(
|
let injector = ReflectiveInjector.resolveAndCreate(
|
||||||
[Location, provide(LocationStrategy, {useValue: locationStrategy}), provider]);
|
[Location, provide(LocationStrategy, {useValue: locationStrategy}), provider]);
|
||||||
return location = injector.get(Location);
|
return location = injector.get(Location);
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import {Injectable, Injector, Key, bind, provide} from "angular2/core";
|
import {Injectable, ReflectiveInjector, ReflectiveKey, bind, provide} from "angular2/core";
|
||||||
import {reflector} from 'angular2/src/core/reflection/reflection';
|
import {reflector} from 'angular2/src/core/reflection/reflection';
|
||||||
import {ReflectionCapabilities} from 'angular2/src/core/reflection/reflection_capabilities';
|
import {ReflectionCapabilities} from 'angular2/src/core/reflection/reflection_capabilities';
|
||||||
import {getIntParameter, bindAction, microBenchmark} from 'angular2/src/testing/benchmark_util';
|
import {getIntParameter, bindAction, microBenchmark} from 'angular2/src/testing/benchmark_util';
|
||||||
@ -17,10 +17,10 @@ export function main() {
|
|||||||
// This benchmark does not use bootstrap and needs to create a reflector
|
// This benchmark does not use bootstrap and needs to create a reflector
|
||||||
setupReflector();
|
setupReflector();
|
||||||
var bindings = [A, B, C, D, E];
|
var bindings = [A, B, C, D, E];
|
||||||
var injector = Injector.resolveAndCreate(bindings);
|
var injector = ReflectiveInjector.resolveAndCreate(bindings);
|
||||||
|
|
||||||
var D_KEY = Key.get(D);
|
var D_KEY = ReflectiveKey.get(D);
|
||||||
var E_KEY = Key.get(E);
|
var E_KEY = ReflectiveKey.get(E);
|
||||||
var childInjector = injector.resolveAndCreateChild([])
|
var childInjector = injector.resolveAndCreateChild([])
|
||||||
.resolveAndCreateChild([])
|
.resolveAndCreateChild([])
|
||||||
.resolveAndCreateChild([])
|
.resolveAndCreateChild([])
|
||||||
@ -29,7 +29,7 @@ export function main() {
|
|||||||
|
|
||||||
var variousProviders = [A, provide(B, {useClass: C}), [D, [E]], provide(F, {useValue: 6})];
|
var variousProviders = [A, provide(B, {useClass: C}), [D, [E]], provide(F, {useValue: 6})];
|
||||||
|
|
||||||
var variousProvidersResolved = Injector.resolve(variousProviders);
|
var variousProvidersResolved = ReflectiveInjector.resolve(variousProviders);
|
||||||
|
|
||||||
function getByToken() {
|
function getByToken() {
|
||||||
for (var i = 0; i < iterations; ++i) {
|
for (var i = 0; i < iterations; ++i) {
|
||||||
@ -63,7 +63,7 @@ export function main() {
|
|||||||
*/
|
*/
|
||||||
function createVariety() {
|
function createVariety() {
|
||||||
for (var i = 0; i < iterations; ++i) {
|
for (var i = 0; i < iterations; ++i) {
|
||||||
Injector.resolveAndCreate(variousProviders);
|
ReflectiveInjector.resolveAndCreate(variousProviders);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -72,7 +72,7 @@ export function main() {
|
|||||||
*/
|
*/
|
||||||
function createVarietyResolved() {
|
function createVarietyResolved() {
|
||||||
for (var i = 0; i < iterations; ++i) {
|
for (var i = 0; i < iterations; ++i) {
|
||||||
Injector.fromResolvedProviders(variousProvidersResolved);
|
ReflectiveInjector.fromResolvedProviders(variousProvidersResolved);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -19,4 +19,4 @@ export {MeasureValues} from './src/measure_values';
|
|||||||
export {MultiMetric} from './src/metric/multi_metric';
|
export {MultiMetric} from './src/metric/multi_metric';
|
||||||
export {MultiReporter} from './src/reporter/multi_reporter';
|
export {MultiReporter} from './src/reporter/multi_reporter';
|
||||||
|
|
||||||
export {bind, provide, Injector, OpaqueToken} from 'angular2/src/core/di';
|
export {bind, provide, Injector, ReflectiveInjector, OpaqueToken} from 'angular2/src/core/di';
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import {Injector, bind, provide, Provider} from 'angular2/src/core/di';
|
import {Injector, bind, provide, Provider, ReflectiveInjector} from 'angular2/src/core/di';
|
||||||
import {isPresent, isBlank} from 'angular2/src/facade/lang';
|
import {isPresent, isBlank} from 'angular2/src/facade/lang';
|
||||||
import {PromiseWrapper} from 'angular2/src/facade/async';
|
import {PromiseWrapper} from 'angular2/src/facade/async';
|
||||||
|
|
||||||
@ -52,7 +52,7 @@ export class Runner {
|
|||||||
sampleBindings.push(bindings);
|
sampleBindings.push(bindings);
|
||||||
}
|
}
|
||||||
|
|
||||||
var inj = Injector.resolveAndCreate(sampleBindings);
|
var inj = ReflectiveInjector.resolveAndCreate(sampleBindings);
|
||||||
var adapter = inj.get(WebDriverAdapter);
|
var adapter = inj.get(WebDriverAdapter);
|
||||||
|
|
||||||
return PromiseWrapper
|
return PromiseWrapper
|
||||||
@ -66,7 +66,7 @@ export class Runner {
|
|||||||
// Only WebDriverAdapter is reused.
|
// Only WebDriverAdapter is reused.
|
||||||
// TODO vsavkin consider changing it when toAsyncFactory is added back or when child
|
// TODO vsavkin consider changing it when toAsyncFactory is added back or when child
|
||||||
// injectors are handled better.
|
// injectors are handled better.
|
||||||
var injector = Injector.resolveAndCreate([
|
var injector = ReflectiveInjector.resolveAndCreate([
|
||||||
sampleBindings,
|
sampleBindings,
|
||||||
bind(Options.CAPABILITIES).toValue(capabilities),
|
bind(Options.CAPABILITIES).toValue(capabilities),
|
||||||
bind(Options.USER_AGENT).toValue(userAgent),
|
bind(Options.USER_AGENT).toValue(userAgent),
|
||||||
|
@ -14,11 +14,11 @@ import {
|
|||||||
import {ListWrapper} from 'angular2/src/facade/collection';
|
import {ListWrapper} from 'angular2/src/facade/collection';
|
||||||
import {PromiseWrapper} from 'angular2/src/facade/async';
|
import {PromiseWrapper} from 'angular2/src/facade/async';
|
||||||
|
|
||||||
import {Metric, MultiMetric, bind, provide, Injector} from 'benchpress/common';
|
import {Metric, MultiMetric, bind, provide, ReflectiveInjector} from 'benchpress/common';
|
||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
function createMetric(ids: any[]) {
|
function createMetric(ids: any[]) {
|
||||||
var m = Injector.resolveAndCreate([
|
var m = ReflectiveInjector.resolveAndCreate([
|
||||||
ids.map(id => provide(id, {useValue: new MockMetric(id)})),
|
ids.map(id => provide(id, {useValue: new MockMetric(id)})),
|
||||||
MultiMetric.createBindings(ids)
|
MultiMetric.createBindings(ids)
|
||||||
])
|
])
|
||||||
|
@ -22,7 +22,7 @@ import {
|
|||||||
PerfLogFeatures,
|
PerfLogFeatures,
|
||||||
bind,
|
bind,
|
||||||
provide,
|
provide,
|
||||||
Injector,
|
ReflectiveInjector,
|
||||||
Options
|
Options
|
||||||
} from 'benchpress/common';
|
} from 'benchpress/common';
|
||||||
|
|
||||||
@ -72,7 +72,7 @@ export function main() {
|
|||||||
if (isPresent(requestCount)) {
|
if (isPresent(requestCount)) {
|
||||||
bindings.push(bind(Options.REQUEST_COUNT).toValue(requestCount));
|
bindings.push(bind(Options.REQUEST_COUNT).toValue(requestCount));
|
||||||
}
|
}
|
||||||
return Injector.resolveAndCreate(bindings).get(PerflogMetric);
|
return ReflectiveInjector.resolveAndCreate(bindings).get(PerflogMetric);
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('perflog metric', () => {
|
describe('perflog metric', () => {
|
||||||
|
@ -16,7 +16,7 @@ import {
|
|||||||
Reporter,
|
Reporter,
|
||||||
bind,
|
bind,
|
||||||
provide,
|
provide,
|
||||||
Injector,
|
ReflectiveInjector,
|
||||||
ConsoleReporter,
|
ConsoleReporter,
|
||||||
SampleDescription,
|
SampleDescription,
|
||||||
MeasureValues
|
MeasureValues
|
||||||
@ -45,7 +45,7 @@ export function main() {
|
|||||||
if (isPresent(columnWidth)) {
|
if (isPresent(columnWidth)) {
|
||||||
bindings.push(bind(ConsoleReporter.COLUMN_WIDTH).toValue(columnWidth));
|
bindings.push(bind(ConsoleReporter.COLUMN_WIDTH).toValue(columnWidth));
|
||||||
}
|
}
|
||||||
reporter = Injector.resolveAndCreate(bindings).get(ConsoleReporter);
|
reporter = ReflectiveInjector.resolveAndCreate(bindings).get(ConsoleReporter);
|
||||||
}
|
}
|
||||||
|
|
||||||
it('should print the sample id, description and table header', () => {
|
it('should print the sample id, description and table header', () => {
|
||||||
|
@ -17,7 +17,7 @@ import {PromiseWrapper} from 'angular2/src/facade/async';
|
|||||||
import {
|
import {
|
||||||
bind,
|
bind,
|
||||||
provide,
|
provide,
|
||||||
Injector,
|
ReflectiveInjector,
|
||||||
SampleDescription,
|
SampleDescription,
|
||||||
MeasureValues,
|
MeasureValues,
|
||||||
Options
|
Options
|
||||||
@ -43,7 +43,7 @@ export function main() {
|
|||||||
return PromiseWrapper.resolve(null);
|
return PromiseWrapper.resolve(null);
|
||||||
})
|
})
|
||||||
];
|
];
|
||||||
return Injector.resolveAndCreate(bindings).get(JsonFileReporter);
|
return ReflectiveInjector.resolveAndCreate(bindings).get(JsonFileReporter);
|
||||||
}
|
}
|
||||||
|
|
||||||
it('should write all data into a file', inject([AsyncTestCompleter], (async) => {
|
it('should write all data into a file', inject([AsyncTestCompleter], (async) => {
|
||||||
|
@ -14,11 +14,18 @@ import {
|
|||||||
import {PromiseWrapper} from 'angular2/src/facade/async';
|
import {PromiseWrapper} from 'angular2/src/facade/async';
|
||||||
import {DateWrapper} from 'angular2/src/facade/lang';
|
import {DateWrapper} from 'angular2/src/facade/lang';
|
||||||
|
|
||||||
import {Reporter, MultiReporter, bind, provide, Injector, MeasureValues} from 'benchpress/common';
|
import {
|
||||||
|
Reporter,
|
||||||
|
MultiReporter,
|
||||||
|
bind,
|
||||||
|
provide,
|
||||||
|
ReflectiveInjector,
|
||||||
|
MeasureValues
|
||||||
|
} from 'benchpress/common';
|
||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
function createReporters(ids: any[]) {
|
function createReporters(ids: any[]) {
|
||||||
var r = Injector.resolveAndCreate([
|
var r = ReflectiveInjector.resolveAndCreate([
|
||||||
ids.map(id => provide(id, {useValue: new MockReporter(id)})),
|
ids.map(id => provide(id, {useValue: new MockReporter(id)})),
|
||||||
MultiReporter.createBindings(ids)
|
MultiReporter.createBindings(ids)
|
||||||
])
|
])
|
||||||
|
@ -17,6 +17,7 @@ import {
|
|||||||
Validator,
|
Validator,
|
||||||
bind,
|
bind,
|
||||||
provide,
|
provide,
|
||||||
|
ReflectiveInjector,
|
||||||
Injector,
|
Injector,
|
||||||
Metric,
|
Metric,
|
||||||
Options,
|
Options,
|
||||||
@ -28,7 +29,7 @@ import {PromiseWrapper} from 'angular2/src/facade/async';
|
|||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
describe('runner', () => {
|
describe('runner', () => {
|
||||||
var injector: Injector;
|
var injector: ReflectiveInjector;
|
||||||
var runner;
|
var runner;
|
||||||
|
|
||||||
function createRunner(defaultBindings = null): Runner {
|
function createRunner(defaultBindings = null): Runner {
|
||||||
|
@ -22,7 +22,7 @@ import {
|
|||||||
Reporter,
|
Reporter,
|
||||||
bind,
|
bind,
|
||||||
provide,
|
provide,
|
||||||
Injector,
|
ReflectiveInjector,
|
||||||
Options,
|
Options,
|
||||||
MeasureValues
|
MeasureValues
|
||||||
} from 'benchpress/common';
|
} from 'benchpress/common';
|
||||||
@ -65,7 +65,7 @@ export function main() {
|
|||||||
bindings.push(bind(Options.PREPARE).toValue(prepare));
|
bindings.push(bind(Options.PREPARE).toValue(prepare));
|
||||||
}
|
}
|
||||||
|
|
||||||
sampler = Injector.resolveAndCreate(bindings).get(Sampler);
|
sampler = ReflectiveInjector.resolveAndCreate(bindings).get(Sampler);
|
||||||
}
|
}
|
||||||
|
|
||||||
it('should call the prepare and execute callbacks using WebDriverAdapter.waitFor',
|
it('should call the prepare and execute callbacks using WebDriverAdapter.waitFor',
|
||||||
|
@ -14,7 +14,7 @@ import {ListWrapper} from 'angular2/src/facade/collection';
|
|||||||
import {
|
import {
|
||||||
Validator,
|
Validator,
|
||||||
RegressionSlopeValidator,
|
RegressionSlopeValidator,
|
||||||
Injector,
|
ReflectiveInjector,
|
||||||
bind,
|
bind,
|
||||||
provide,
|
provide,
|
||||||
MeasureValues
|
MeasureValues
|
||||||
@ -25,7 +25,7 @@ export function main() {
|
|||||||
var validator;
|
var validator;
|
||||||
|
|
||||||
function createValidator({size, metric}) {
|
function createValidator({size, metric}) {
|
||||||
validator = Injector.resolveAndCreate([
|
validator = ReflectiveInjector.resolveAndCreate([
|
||||||
RegressionSlopeValidator.BINDINGS,
|
RegressionSlopeValidator.BINDINGS,
|
||||||
bind(RegressionSlopeValidator.METRIC).toValue(metric),
|
bind(RegressionSlopeValidator.METRIC).toValue(metric),
|
||||||
bind(RegressionSlopeValidator.SAMPLE_SIZE).toValue(size)
|
bind(RegressionSlopeValidator.SAMPLE_SIZE).toValue(size)
|
||||||
|
@ -11,16 +11,24 @@ import {
|
|||||||
import {Date, DateWrapper} from 'angular2/src/facade/lang';
|
import {Date, DateWrapper} from 'angular2/src/facade/lang';
|
||||||
import {ListWrapper} from 'angular2/src/facade/collection';
|
import {ListWrapper} from 'angular2/src/facade/collection';
|
||||||
|
|
||||||
import {Validator, SizeValidator, Injector, bind, provide, MeasureValues} from 'benchpress/common';
|
import {
|
||||||
|
Validator,
|
||||||
|
SizeValidator,
|
||||||
|
ReflectiveInjector,
|
||||||
|
bind,
|
||||||
|
provide,
|
||||||
|
MeasureValues
|
||||||
|
} from 'benchpress/common';
|
||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
describe('size validator', () => {
|
describe('size validator', () => {
|
||||||
var validator;
|
var validator;
|
||||||
|
|
||||||
function createValidator(size) {
|
function createValidator(size) {
|
||||||
validator =
|
validator = ReflectiveInjector.resolveAndCreate([
|
||||||
Injector.resolveAndCreate(
|
SizeValidator.BINDINGS,
|
||||||
[SizeValidator.BINDINGS, bind(SizeValidator.SAMPLE_SIZE).toValue(size)])
|
bind(SizeValidator.SAMPLE_SIZE).toValue(size)
|
||||||
|
])
|
||||||
.get(SizeValidator);
|
.get(SizeValidator);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -14,12 +14,12 @@ import {
|
|||||||
import {isPresent, StringWrapper} from 'angular2/src/facade/lang';
|
import {isPresent, StringWrapper} from 'angular2/src/facade/lang';
|
||||||
import {PromiseWrapper} from 'angular2/src/facade/async';
|
import {PromiseWrapper} from 'angular2/src/facade/async';
|
||||||
|
|
||||||
import {WebDriverExtension, bind, provide, Injector, Options} from 'benchpress/common';
|
import {WebDriverExtension, bind, provide, ReflectiveInjector, Options} from 'benchpress/common';
|
||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
function createExtension(ids: any[], caps) {
|
function createExtension(ids: any[], caps) {
|
||||||
return PromiseWrapper.wrap(() => {
|
return PromiseWrapper.wrap(() => {
|
||||||
return Injector.resolveAndCreate([
|
return ReflectiveInjector.resolveAndCreate([
|
||||||
ids.map(id => provide(id, {useValue: new MockExtension(id)})),
|
ids.map(id => provide(id, {useValue: new MockExtension(id)})),
|
||||||
bind(Options.CAPABILITIES).toValue(caps),
|
bind(Options.CAPABILITIES).toValue(caps),
|
||||||
WebDriverExtension.bindTo(ids)
|
WebDriverExtension.bindTo(ids)
|
||||||
|
@ -18,7 +18,7 @@ import {
|
|||||||
WebDriverExtension,
|
WebDriverExtension,
|
||||||
ChromeDriverExtension,
|
ChromeDriverExtension,
|
||||||
WebDriverAdapter,
|
WebDriverAdapter,
|
||||||
Injector,
|
ReflectiveInjector,
|
||||||
bind,
|
bind,
|
||||||
provide,
|
provide,
|
||||||
Options
|
Options
|
||||||
@ -57,7 +57,8 @@ export function main() {
|
|||||||
userAgent = CHROME44_USER_AGENT;
|
userAgent = CHROME44_USER_AGENT;
|
||||||
}
|
}
|
||||||
log = [];
|
log = [];
|
||||||
extension = Injector.resolveAndCreate([
|
extension =
|
||||||
|
ReflectiveInjector.resolveAndCreate([
|
||||||
ChromeDriverExtension.BINDINGS,
|
ChromeDriverExtension.BINDINGS,
|
||||||
bind(WebDriverAdapter)
|
bind(WebDriverAdapter)
|
||||||
.toValue(new MockDriverAdapter(log, perfRecords, messageMethod)),
|
.toValue(new MockDriverAdapter(log, perfRecords, messageMethod)),
|
||||||
|
@ -18,7 +18,7 @@ import {
|
|||||||
WebDriverExtension,
|
WebDriverExtension,
|
||||||
IOsDriverExtension,
|
IOsDriverExtension,
|
||||||
WebDriverAdapter,
|
WebDriverAdapter,
|
||||||
Injector,
|
ReflectiveInjector,
|
||||||
bind,
|
bind,
|
||||||
provide
|
provide
|
||||||
} from 'benchpress/common';
|
} from 'benchpress/common';
|
||||||
@ -37,10 +37,10 @@ export function main() {
|
|||||||
perfRecords = [];
|
perfRecords = [];
|
||||||
}
|
}
|
||||||
log = [];
|
log = [];
|
||||||
extension =
|
extension = ReflectiveInjector.resolveAndCreate([
|
||||||
Injector.resolveAndCreate([
|
|
||||||
IOsDriverExtension.BINDINGS,
|
IOsDriverExtension.BINDINGS,
|
||||||
provide(WebDriverAdapter, {useValue: new MockDriverAdapter(log, perfRecords)})
|
provide(WebDriverAdapter,
|
||||||
|
{useValue: new MockDriverAdapter(log, perfRecords)})
|
||||||
])
|
])
|
||||||
.get(IOsDriverExtension);
|
.get(IOsDriverExtension);
|
||||||
return extension;
|
return extension;
|
||||||
|
@ -13,12 +13,12 @@ import {publicApi} from 'ts-api-guardian';
|
|||||||
|
|
||||||
const CORE = [
|
const CORE = [
|
||||||
'AbstractProviderError',
|
'AbstractProviderError',
|
||||||
'AbstractProviderError.addKey(injector:Injector, key:Key):void',
|
'AbstractProviderError.addKey(injector:ReflectiveInjector, key:ReflectiveKey):void',
|
||||||
'AbstractProviderError.constructResolvingMessage:Function',
|
'AbstractProviderError.constructResolvingMessage:Function',
|
||||||
'AbstractProviderError.constructor(injector:Injector, key:Key, constructResolvingMessage:Function)',
|
'AbstractProviderError.constructor(injector:ReflectiveInjector, key:ReflectiveKey, constructResolvingMessage:Function)',
|
||||||
'AbstractProviderError.context:any',
|
'AbstractProviderError.context:any',
|
||||||
'AbstractProviderError.injectors:Injector[]',
|
'AbstractProviderError.injectors:ReflectiveInjector[]',
|
||||||
'AbstractProviderError.keys:Key[]',
|
'AbstractProviderError.keys:ReflectiveKey[]',
|
||||||
'AbstractProviderError.message:string',
|
'AbstractProviderError.message:string',
|
||||||
'AfterContentChecked',
|
'AfterContentChecked',
|
||||||
'AfterContentChecked.ngAfterContentChecked():any',
|
'AfterContentChecked.ngAfterContentChecked():any',
|
||||||
@ -106,7 +106,7 @@ const CORE = [
|
|||||||
'ContentChildrenMetadata',
|
'ContentChildrenMetadata',
|
||||||
'ContentChildrenMetadata.constructor(_selector:Type|string, {descendants=false,read=null}:{descendants?:boolean, read?:any})',
|
'ContentChildrenMetadata.constructor(_selector:Type|string, {descendants=false,read=null}:{descendants?:boolean, read?:any})',
|
||||||
'CyclicDependencyError',
|
'CyclicDependencyError',
|
||||||
'CyclicDependencyError.constructor(injector:Injector, key:Key)',
|
'CyclicDependencyError.constructor(injector:ReflectiveInjector, key:ReflectiveKey)',
|
||||||
'DebugNode',
|
'DebugNode',
|
||||||
'DebugNode.componentInstance:any',
|
'DebugNode.componentInstance:any',
|
||||||
'DebugNode.constructor(nativeNode:any, parent:DebugNode, _debugInfo:RenderDebugInfo)',
|
'DebugNode.constructor(nativeNode:any, parent:DebugNode, _debugInfo:RenderDebugInfo)',
|
||||||
@ -135,9 +135,9 @@ const CORE = [
|
|||||||
'DebugElement.removeChild(child:DebugNode):any',
|
'DebugElement.removeChild(child:DebugNode):any',
|
||||||
'DebugElement.triggerEventHandler(eventName:string, eventObj:any):any',
|
'DebugElement.triggerEventHandler(eventName:string, eventObj:any):any',
|
||||||
'asNativeElements(debugEls:DebugElement[]):any',
|
'asNativeElements(debugEls:DebugElement[]):any',
|
||||||
'Dependency',
|
'ReflectiveDependency',
|
||||||
'Dependency.constructor(key:Key, optional:boolean, lowerBoundVisibility:any, upperBoundVisibility:any, properties:any[])',
|
'ReflectiveDependency.constructor(key:ReflectiveKey, optional:boolean, lowerBoundVisibility:any, upperBoundVisibility:any, properties:any[])',
|
||||||
'Dependency.fromKey(key:Key):Dependency',
|
'ReflectiveDependency.fromKey(key:ReflectiveKey):ReflectiveDependency',
|
||||||
'DependencyMetadata',
|
'DependencyMetadata',
|
||||||
'DependencyMetadata.token:any',
|
'DependencyMetadata.token:any',
|
||||||
'DirectiveDecorator',
|
'DirectiveDecorator',
|
||||||
@ -158,7 +158,7 @@ const CORE = [
|
|||||||
'DoCheck.ngDoCheck():any',
|
'DoCheck.ngDoCheck():any',
|
||||||
'DynamicComponentLoader',
|
'DynamicComponentLoader',
|
||||||
'DynamicComponentLoader.loadAsRoot(type:Type, overrideSelectorOrNode:string, injector:Injector, onDispose:() => void, projectableNodes:any[][]):Promise<ComponentRef>',
|
'DynamicComponentLoader.loadAsRoot(type:Type, overrideSelectorOrNode:string, injector:Injector, onDispose:() => void, projectableNodes:any[][]):Promise<ComponentRef>',
|
||||||
'DynamicComponentLoader.loadNextToLocation(type:Type, location:ViewContainerRef, providers:ResolvedProvider[], projectableNodes:any[][]):Promise<ComponentRef>',
|
'DynamicComponentLoader.loadNextToLocation(type:Type, location:ViewContainerRef, providers:ResolvedReflectiveProvider[], projectableNodes:any[][]):Promise<ComponentRef>',
|
||||||
'ElementRef',
|
'ElementRef',
|
||||||
'ElementRef.nativeElement:any',
|
'ElementRef.nativeElement:any',
|
||||||
'ElementRef.constructor(nativeElement:any)',
|
'ElementRef.constructor(nativeElement:any)',
|
||||||
@ -203,28 +203,30 @@ const CORE = [
|
|||||||
'InjectableMetadata',
|
'InjectableMetadata',
|
||||||
'InjectableMetadata.constructor()',
|
'InjectableMetadata.constructor()',
|
||||||
'Injector',
|
'Injector',
|
||||||
'Injector.createChildFromResolved(providers:ResolvedProvider[]):Injector',
|
'Injector.THROW_IF_NOT_FOUND:any',
|
||||||
'Injector.debugContext():any',
|
'Injector.get(token:any, notFoundValue:any):any',
|
||||||
'Injector.fromResolvedBindings(providers:ResolvedProvider[]):Injector',
|
'ReflectiveInjector',
|
||||||
'Injector.fromResolvedProviders(providers:ResolvedProvider[]):Injector',
|
'ReflectiveInjector.createChildFromResolved(providers:ResolvedReflectiveProvider[]):ReflectiveInjector',
|
||||||
'Injector.get(token:any):any',
|
'ReflectiveInjector.debugContext():any',
|
||||||
'Injector.getOptional(token:any):any',
|
'ReflectiveInjector.fromResolvedBindings(providers:ResolvedReflectiveProvider[]):ReflectiveInjector',
|
||||||
'Injector.instantiateResolved(provider:ResolvedProvider):any',
|
'ReflectiveInjector.fromResolvedProviders(providers:ResolvedReflectiveProvider[], parent:Injector):ReflectiveInjector',
|
||||||
'Injector.parent:Injector',
|
'ReflectiveInjector.get(token:any, notFoundValue:any):any',
|
||||||
'Injector.resolve(providers:Array<Type|Provider|any[]>):ResolvedProvider[]',
|
'ReflectiveInjector.instantiateResolved(provider:ResolvedReflectiveProvider):any',
|
||||||
'Injector.resolveAndCreate(providers:Array<Type|Provider|any[]>):Injector',
|
'ReflectiveInjector.parent:Injector',
|
||||||
'Injector.resolveAndCreateChild(providers:Array<Type|Provider|any[]>):Injector',
|
'ReflectiveInjector.resolve(providers:Array<Type|Provider|any[]>):ResolvedReflectiveProvider[]',
|
||||||
'Injector.resolveAndInstantiate(provider:Type|Provider):any',
|
'ReflectiveInjector.resolveAndCreate(providers:Array<Type|Provider|any[]>, parent:Injector):ReflectiveInjector',
|
||||||
|
'ReflectiveInjector.resolveAndCreateChild(providers:Array<Type|Provider|any[]>):ReflectiveInjector',
|
||||||
|
'ReflectiveInjector.resolveAndInstantiate(provider:Type|Provider):any',
|
||||||
'InputMetadataFactory',
|
'InputMetadataFactory',
|
||||||
'InputMetadata',
|
'InputMetadata',
|
||||||
'InputMetadata.constructor(bindingPropertyName:string)',
|
'InputMetadata.constructor(bindingPropertyName:string)',
|
||||||
'InstantiationError',
|
'InstantiationError',
|
||||||
'InstantiationError.addKey(injector:Injector, key:Key):void',
|
'InstantiationError.addKey(injector:ReflectiveInjector, key:ReflectiveKey):void',
|
||||||
'InstantiationError.causeKey:Key',
|
'InstantiationError.causeKey:ReflectiveKey',
|
||||||
'InstantiationError.constructor(injector:Injector, originalException:any, originalStack:any, key:Key)',
|
'InstantiationError.constructor(injector:ReflectiveInjector, originalException:any, originalStack:any, key:ReflectiveKey)',
|
||||||
'InstantiationError.context:any',
|
'InstantiationError.context:any',
|
||||||
'InstantiationError.injectors:Injector[]',
|
'InstantiationError.injectors:ReflectiveInjector[]',
|
||||||
'InstantiationError.keys:Key[]',
|
'InstantiationError.keys:ReflectiveKey[]',
|
||||||
'InstantiationError.wrapperMessage:string',
|
'InstantiationError.wrapperMessage:string',
|
||||||
'InvalidProviderError',
|
'InvalidProviderError',
|
||||||
'InvalidProviderError.constructor(provider:any)',
|
'InvalidProviderError.constructor(provider:any)',
|
||||||
@ -239,11 +241,11 @@ const CORE = [
|
|||||||
'IterableDiffers.create(factories:IterableDifferFactory[], parent:IterableDiffers):IterableDiffers',
|
'IterableDiffers.create(factories:IterableDifferFactory[], parent:IterableDiffers):IterableDiffers',
|
||||||
'IterableDiffers.extend(factories:IterableDifferFactory[]):Provider',
|
'IterableDiffers.extend(factories:IterableDifferFactory[]):Provider',
|
||||||
'IterableDiffers.find(iterable:any):IterableDifferFactory',
|
'IterableDiffers.find(iterable:any):IterableDifferFactory',
|
||||||
'Key',
|
'ReflectiveKey',
|
||||||
'Key.constructor(token:Object, id:number)',
|
'ReflectiveKey.constructor(token:Object, id:number)',
|
||||||
'Key.displayName:string',
|
'ReflectiveKey.displayName:string',
|
||||||
'Key.get(token:Object):Key',
|
'ReflectiveKey.get(token:Object):ReflectiveKey',
|
||||||
'Key.numberOfKeys:number',
|
'ReflectiveKey.numberOfKeys:number',
|
||||||
'KeyValueChangeRecord',
|
'KeyValueChangeRecord',
|
||||||
'KeyValueChangeRecord.constructor(key:any)',
|
'KeyValueChangeRecord.constructor(key:any)',
|
||||||
'KeyValueChangeRecord.currentValue:any',
|
'KeyValueChangeRecord.currentValue:any',
|
||||||
@ -278,7 +280,7 @@ const CORE = [
|
|||||||
'NoAnnotationError',
|
'NoAnnotationError',
|
||||||
'NoAnnotationError.constructor(typeOrFunc:any, params:any[][])',
|
'NoAnnotationError.constructor(typeOrFunc:any, params:any[][])',
|
||||||
'NoProviderError',
|
'NoProviderError',
|
||||||
'NoProviderError.constructor(injector:Injector, key:Key)',
|
'NoProviderError.constructor(injector:ReflectiveInjector, key:ReflectiveKey)',
|
||||||
'OnChanges',
|
'OnChanges',
|
||||||
'OnChanges.ngOnChanges(changes:{[key:string]:SimpleChange}):any',
|
'OnChanges.ngOnChanges(changes:{[key:string]:SimpleChange}):any',
|
||||||
'OnDestroy',
|
'OnDestroy',
|
||||||
@ -393,13 +395,13 @@ const CORE = [
|
|||||||
'Renderer.setElementProperty(renderElement:any, propertyName:string, propertyValue:any):void',
|
'Renderer.setElementProperty(renderElement:any, propertyName:string, propertyValue:any):void',
|
||||||
'Renderer.setElementStyle(renderElement:any, styleName:string, styleValue:string):any',
|
'Renderer.setElementStyle(renderElement:any, styleName:string, styleValue:string):any',
|
||||||
'Renderer.setText(renderNode:any, text:string):any',
|
'Renderer.setText(renderNode:any, text:string):any',
|
||||||
'ResolvedBinding',
|
'ResolvedReflectiveBinding',
|
||||||
'ResolvedFactory',
|
'ResolvedReflectiveFactory',
|
||||||
'ResolvedFactory.constructor(factory:Function, dependencies:Dependency[])',
|
'ResolvedReflectiveFactory.constructor(factory:Function, dependencies:ReflectiveDependency[])',
|
||||||
'ResolvedProvider',
|
'ResolvedReflectiveProvider',
|
||||||
'ResolvedProvider.key:Key',
|
'ResolvedReflectiveProvider.key:ReflectiveKey',
|
||||||
'ResolvedProvider.multiProvider:boolean',
|
'ResolvedReflectiveProvider.multiProvider:boolean',
|
||||||
'ResolvedProvider.resolvedFactories:ResolvedFactory[]',
|
'ResolvedReflectiveProvider.resolvedFactories:ResolvedReflectiveFactory[]',
|
||||||
'RootRenderer',
|
'RootRenderer',
|
||||||
'RootRenderer.renderComponent(componentType:RenderComponentType):Renderer',
|
'RootRenderer.renderComponent(componentType:RenderComponentType):Renderer',
|
||||||
'SelfMetadataFactory',
|
'SelfMetadataFactory',
|
||||||
@ -443,9 +445,11 @@ const CORE = [
|
|||||||
'ViewContainerRef',
|
'ViewContainerRef',
|
||||||
'ViewContainerRef.clear():void',
|
'ViewContainerRef.clear():void',
|
||||||
'ViewContainerRef.createEmbeddedView(templateRef:TemplateRef, index:number):EmbeddedViewRef',
|
'ViewContainerRef.createEmbeddedView(templateRef:TemplateRef, index:number):EmbeddedViewRef',
|
||||||
'ViewContainerRef.createComponent(componentFactory:ComponentFactory, index:number, dynamicallyCreatedProviders:ResolvedProvider[], projectableNodes:any[][]):ComponentRef',
|
'ViewContainerRef.createComponent(componentFactory:ComponentFactory, index:number, injector:Injector, projectableNodes:any[][]):ComponentRef',
|
||||||
'ViewContainerRef.detach(index:number):ViewRef',
|
'ViewContainerRef.detach(index:number):ViewRef',
|
||||||
'ViewContainerRef.element:ElementRef',
|
'ViewContainerRef.element:ElementRef',
|
||||||
|
'ViewContainerRef.injector:Injector',
|
||||||
|
'ViewContainerRef.parentInjector:Injector',
|
||||||
'ViewContainerRef.get(index:number):ViewRef',
|
'ViewContainerRef.get(index:number):ViewRef',
|
||||||
'ViewContainerRef.indexOf(viewRef:ViewRef):number',
|
'ViewContainerRef.indexOf(viewRef:ViewRef):number',
|
||||||
'ViewContainerRef.insert(viewRef:ViewRef, index:number):ViewRef',
|
'ViewContainerRef.insert(viewRef:ViewRef, index:number):ViewRef',
|
||||||
@ -820,8 +824,7 @@ const COMMON = [
|
|||||||
'var workaround_empty_observable_list_diff:any'
|
'var workaround_empty_observable_list_diff:any'
|
||||||
];
|
];
|
||||||
|
|
||||||
const COMPILER =
|
const COMPILER = [
|
||||||
[
|
|
||||||
'AttrAst',
|
'AttrAst',
|
||||||
'AttrAst.constructor(name:string, value:string, sourceSpan:ParseSourceSpan)',
|
'AttrAst.constructor(name:string, value:string, sourceSpan:ParseSourceSpan)',
|
||||||
'AttrAst.visit(visitor:TemplateAstVisitor, context:any):any',
|
'AttrAst.visit(visitor:TemplateAstVisitor, context:any):any',
|
||||||
@ -1054,7 +1057,7 @@ const COMPILER =
|
|||||||
'ViewResolver.constructor(_reflector:ReflectorReader)',
|
'ViewResolver.constructor(_reflector:ReflectorReader)',
|
||||||
'ViewResolver.resolve(component:Type):ViewMetadata',
|
'ViewResolver.resolve(component:Type):ViewMetadata',
|
||||||
'createOfflineCompileUrlResolver():UrlResolver'
|
'createOfflineCompileUrlResolver():UrlResolver'
|
||||||
];
|
];
|
||||||
|
|
||||||
const INSTRUMENTATION = [
|
const INSTRUMENTATION = [
|
||||||
'WtfScopeFn',
|
'WtfScopeFn',
|
||||||
|
Loading…
x
Reference in New Issue
Block a user