|
| 1 | +import {isBlank} from 'angular2/src/facade/lang'; |
| 2 | +import {Injector, InjectorFactory, THROW_IF_NOT_FOUND} from './injector'; |
| 3 | + |
| 4 | +/** |
| 5 | + * An simple injector based on a Map of values. |
| 6 | + */ |
| 7 | +export class MapInjector implements Injector { |
| 8 | + static createFactory(values?: Map<any, any>, |
| 9 | + factories?: Map<any, (injector: Injector) => any>): InjectorFactory<any> { |
| 10 | + return new MapInjectorFactory(values, factories); |
| 11 | + } |
| 12 | + |
| 13 | + private _instances: Map<any, any> = new Map<any, any>(); |
| 14 | + private _factories: Map<any, (injector: Injector) => any>; |
| 15 | + private _values: Map<any, any>; |
| 16 | + |
| 17 | + constructor(private _parent: Injector = null, values: Map<any, any> = null, |
| 18 | + factories: Map<any, (injector: Injector) => any> = null) { |
| 19 | + if (isBlank(values)) { |
| 20 | + values = new Map<any, any>(); |
| 21 | + } |
| 22 | + this._values = values; |
| 23 | + if (isBlank(factories)) { |
| 24 | + factories = new Map<any, any>(); |
| 25 | + } |
| 26 | + this._factories = factories; |
| 27 | + if (isBlank(this._parent)) { |
| 28 | + this._parent = Injector.NULL; |
| 29 | + } |
| 30 | + } |
| 31 | + get(token: any, notFoundValue: any = THROW_IF_NOT_FOUND): any { |
| 32 | + if (token === Injector) { |
| 33 | + return this; |
| 34 | + } |
| 35 | + if (this._values.has(token)) { |
| 36 | + return this._values.get(token); |
| 37 | + } |
| 38 | + if (this._instances.has(token)) { |
| 39 | + return this._instances.get(token); |
| 40 | + } |
| 41 | + if (this._factories.has(token)) { |
| 42 | + var instance = this._factories.get(token)(this); |
| 43 | + this._instances.set(token, instance); |
| 44 | + return instance; |
| 45 | + } |
| 46 | + return this._parent.get(token, notFoundValue); |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +/** |
| 51 | + * InjectorFactory for MapInjector. |
| 52 | + */ |
| 53 | +export class MapInjectorFactory implements InjectorFactory<any> { |
| 54 | + constructor(private _values: Map<any, any> = null, |
| 55 | + private _factories: Map<any, (injector: Injector) => any> = null) {} |
| 56 | + |
| 57 | + create(parent: Injector = null, context: any = null): Injector { |
| 58 | + return new MapInjector(parent, this._values, this._factories); |
| 59 | + } |
| 60 | +} |
0 commit comments