angular
angular copied to clipboard
More typed and explicit `Injector` class
NOTE: This interface requires Dart 2.0 for reified type parameters with generic methods. Since this is currently only implemented in dartdevc we won't be landing this change to replace the current Injector until at least dart2js implements the same support.
EDIT: See https://github.com/dart-lang/angular/issues/555#issuecomment-398899620 for the latest proposal.
abstract class Injector {
/// Creates an injector that has no providers itself, only delegating to a [parent].
///
/// If a [parent] is not specified, injector always throws if `optional` is not used.
const factory Injector.empty([Injector parent]) = _EmptyInjector;
/// Creates a simple injector that uses a [map] as a backing implementation.
///
/// All keys are used as tokens, and values as the returned instance.
const factory Injector.map(Map<Object, Object> map, [Injector parent]) = _MapInjector;
/// Injects and returns an instance of type [T].
///
/// ```dart
/// final rpcService = injector.get<RpcService>();
/// ```
///
/// May optionally use an [InjectionToken] instead of [Type]:
/// ```dart
/// const cachedRpcService = const InjectionToken<RpcService>(#cached);
/// ...
/// final rpcService = injector.get(token: cachedRpcService);
/// ```
///
/// If [optional] is set, returns `null` if not found, otherwise throws [InjectionError].
T inject<T>({InjectionToken<T> token, bool optional: false});
/// Injects and returns an instance of type [T] from an ancestor injector.
///
/// Unlike [inject], a token provided from the same injector is not used.
T injectFromAncestry<T>({InjectionToken<T> token, bool optional: false});
/// Injects and returns an instance of type [T] from the parent injector.
///
/// Unlike [inject], a token can _only_ be provided from the direct parent.
T injectFromParent<T>({InjectionToken<T> token, bool optional: false};
/// Injects and returns an instance of type [T] from this injector.
///
/// Unlike [inject], a token can _only_ be provided from _this_ injector.
T injectFromSelf<T>({InjectionToken<T> token, bool optional: false});
}
We're still waiting on this (there is no support for this in the current version of Dart2JS).
I think we are going to go with a subset of this API, that is:
- [x] Change
MultiToken<T>to extendOpaqueToken<List<T>> - [ ] (Soft?) Deprecate
Injector.get(Object token, [Object defaultValue])... preferring: - [ ] Add
Injector.getType<T>([T defaultValue]) - [ ] Add
Injector.getToken<T>(OpaqueToken<T> token)
The breaking changes we want to get in by 5.0.0, the rest can happen after.