From 0c4fbfc8e237b83024c9d5c58123bf16d0b604b7 Mon Sep 17 00:00:00 2001 From: Pawel Kozlowski Date: Sat, 21 Feb 2015 15:18:06 +0100 Subject: [PATCH] feat(di): introduce aliasing Closes #710 Closes #747 --- modules/angular2/docs/di/di.md | 12 +++++++++++- modules/angular2/src/di/binding.js | 9 +++++++++ modules/angular2/test/di/injector_spec.js | 22 +++++++++++++++++++++- 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/modules/angular2/docs/di/di.md b/modules/angular2/docs/di/di.md index 88cd9c33ce..549762b57f 100644 --- a/modules/angular2/docs/di/di.md +++ b/modules/angular2/docs/di/di.md @@ -96,7 +96,7 @@ var car = child.get(Car); // uses the Car binding from the parent injector and E ## Bindings -You can bind to a class, a value, or a factory +You can bind to a class, a value, or a factory. It is also possible to alias existing bindings. ``` var inj = new Injector([ @@ -128,6 +128,16 @@ var inj = new Injector([ ]); ``` +If you want to alias an existing binding, you can do so using `toAlias`: + +``` +var inj = new Injector([ + bind(Engine).toClass(Engine), + bind("engine!").toAlias(Engine) +]); +``` +which implies `inj.get(Engine) === inj.get("engine!")`. + Note that tokens and factory functions are decoupled. ``` diff --git a/modules/angular2/src/di/binding.js b/modules/angular2/src/di/binding.js index 690a8a192d..c89af011e6 100644 --- a/modules/angular2/src/di/binding.js +++ b/modules/angular2/src/di/binding.js @@ -60,6 +60,15 @@ export class BindingBuilder { ); } + toAlias(aliasToken):Binding { + return new Binding( + Key.get(this.token), + (aliasInstance) => aliasInstance, + [new Dependency(Key.get(aliasToken), false, false, [])], + false + ); + } + toFactory(factoryFunction:Function, dependencies:List = null):Binding { return new Binding( Key.get(this.token), diff --git a/modules/angular2/test/di/injector_spec.js b/modules/angular2/test/di/injector_spec.js index ee2ef4bfc8..03c7de1edb 100644 --- a/modules/angular2/test/di/injector_spec.js +++ b/modules/angular2/test/di/injector_spec.js @@ -128,6 +128,26 @@ export function main() { expect(car.engine).toBeAnInstanceOf(Engine); }); + it('should bind to an alias', function() { + var injector = new Injector([ + Engine, + bind(SportsCar).toClass(SportsCar), + bind(Car).toAlias(SportsCar) + ]); + + var car = injector.get(Car); + var sportsCar = injector.get(SportsCar); + expect(car).toBeAnInstanceOf(SportsCar); + expect(car).toBe(sportsCar); + }); + + it('should throw when the aliased binding does not exist', function () { + var injector = new Injector([ + bind('car').toAlias(SportsCar) + ]); + expect(() => injector.get('car')).toThrowError('No provider for SportsCar! (car -> SportsCar)'); + }); + it('should support overriding factory dependencies', function () { var injector = new Injector([ Engine, @@ -324,4 +344,4 @@ export function main() { }); }); }); -} \ No newline at end of file +}