72 lines
1.9 KiB
TypeScript
Raw Normal View History

2015-04-15 22:35:38 +00:00
import {MapWrapper} from 'angular2/src/facade/collection';
import {stringify, CONST, Type, isBlank, BaseException} from 'angular2/src/facade/lang';
2015-05-08 17:57:03 -07:00
import {TypeLiteral} from './type_literal';
import {resolveForwardRef} from './forward_ref';
2015-05-08 17:57:03 -07:00
export {TypeLiteral} from './type_literal';
2015-04-15 22:35:38 +00:00
/**
* A unique object used for retrieving items from the {@link Injector}.
2015-04-15 22:35:38 +00:00
*
* Keys have:
* - a system-wide unique `id`.
* - a `token`, usually the `Type` of the instance.
2015-04-15 22:35:38 +00:00
*
* Keys are used internally by the {@link Injector} because their system-wide unique `id`s allow the
2015-04-17 03:29:05 -07:00
* injector to index in arrays rather than looking up items in maps.
2015-04-15 22:35:38 +00:00
*
* @exportedAs angular2/di
*/
export class Key {
2015-05-08 17:57:03 -07:00
/**
* @private
*/
2015-06-17 10:12:06 +02:00
constructor(public token: Object, public id: number) {
if (isBlank(token)) {
throw new BaseException('Token must be defined!');
}
}
2015-06-17 10:12:06 +02:00
get displayName(): string { return stringify(this.token); }
2015-04-15 22:35:38 +00:00
/**
* Retrieves a `Key` for a token.
2015-04-15 22:35:38 +00:00
*/
static get(token): Key { return _globalKeyRegistry.get(resolveForwardRef(token)); }
2014-10-20 15:17:06 -04:00
2015-04-15 22:35:38 +00:00
/**
* @returns the number of keys registered in the system.
2015-04-15 22:35:38 +00:00
*/
static get numberOfKeys(): number { return _globalKeyRegistry.numberOfKeys; }
2014-10-09 12:09:50 -04:00
}
2015-04-15 22:35:38 +00:00
/**
* @private
*/
export class KeyRegistry {
private _allKeys: Map<Object, Key> = new Map();
get(token: Object): Key {
if (token instanceof Key) return token;
2015-05-08 17:57:03 -07:00
// TODO: workaround for https://github.com/Microsoft/TypeScript/issues/3123
var theToken = token;
if (token instanceof TypeLiteral) {
theToken = token.type;
}
token = theToken;
2015-06-17 21:42:56 -07:00
if (this._allKeys.has(token)) {
return this._allKeys.get(token);
}
var newKey = new Key(token, Key.numberOfKeys);
this._allKeys.set(token, newKey);
return newKey;
}
2015-06-17 10:12:06 +02:00
get numberOfKeys(): number { return MapWrapper.size(this._allKeys); }
}
var _globalKeyRegistry = new KeyRegistry();