| OLD | NEW |
| (Empty) | |
| 1 library di.dynamic_injector; |
| 2 |
| 3 import 'di.dart'; |
| 4 import 'mirrors.dart'; |
| 5 |
| 6 /** |
| 7 * Dynamic implementation of [Injector] that uses mirrors. |
| 8 */ |
| 9 class DynamicInjector extends Injector { |
| 10 |
| 11 DynamicInjector({List<Module> modules, String name, |
| 12 bool allowImplicitInjection: false}) |
| 13 : super(modules: modules, name: name, |
| 14 allowImplicitInjection: allowImplicitInjection); |
| 15 |
| 16 DynamicInjector._fromParent(List<Module> modules, Injector parent, {name}) |
| 17 : super.fromParent(modules, parent, name: name); |
| 18 |
| 19 newFromParent(List<Module> modules, String name) { |
| 20 return new DynamicInjector._fromParent(modules, this, name: name); |
| 21 } |
| 22 |
| 23 Object newInstanceOf(Type type, ObjectFactory getInstanceByType, |
| 24 Injector requestor, error) { |
| 25 var classMirror = reflectType(type); |
| 26 if (classMirror is TypedefMirror) { |
| 27 throw new NoProviderError(error('No implementation provided ' |
| 28 'for ${getSymbolName(classMirror.qualifiedName)} typedef!')); |
| 29 } |
| 30 |
| 31 MethodMirror ctor = classMirror.declarations[classMirror.simpleName]; |
| 32 |
| 33 resolveArgument(int pos) { |
| 34 ParameterMirror p = ctor.parameters[pos]; |
| 35 return getInstanceByType(getReflectedTypeWorkaround(p.type), requestor); |
| 36 } |
| 37 |
| 38 var args = new List.generate(ctor.parameters.length, resolveArgument, |
| 39 growable: false); |
| 40 return classMirror.newInstance(ctor.constructorName, args).reflectee; |
| 41 } |
| 42 |
| 43 /** |
| 44 * Invoke given function and inject all its arguments. |
| 45 * |
| 46 * Returns whatever the function returns. |
| 47 */ |
| 48 dynamic invoke(Function fn) { |
| 49 ClosureMirror cm = reflect(fn); |
| 50 MethodMirror mm = cm.function; |
| 51 int position = 0; |
| 52 List args = mm.parameters.map((ParameterMirror parameter) { |
| 53 try { |
| 54 return get(getReflectedTypeWorkaround(parameter.type)); |
| 55 } on NoProviderError catch (e) { |
| 56 throw new NoProviderError(e.message); |
| 57 } finally { |
| 58 position++; |
| 59 } |
| 60 }).toList(); |
| 61 |
| 62 return cm.apply(args).reflectee; |
| 63 } |
| 64 } |
| OLD | NEW |