Skip to content

Commit 0c4fbfc

Browse files
feat(di): introduce aliasing
Closes angular#710 Closes angular#747
1 parent a80105f commit 0c4fbfc

File tree

3 files changed

+41
-2
lines changed

3 files changed

+41
-2
lines changed

modules/angular2/docs/di/di.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ var car = child.get(Car); // uses the Car binding from the parent injector and E
9696

9797
## Bindings
9898

99-
You can bind to a class, a value, or a factory
99+
You can bind to a class, a value, or a factory. It is also possible to alias existing bindings.
100100

101101
```
102102
var inj = new Injector([
@@ -128,6 +128,16 @@ var inj = new Injector([
128128
]);
129129
```
130130

131+
If you want to alias an existing binding, you can do so using `toAlias`:
132+
133+
```
134+
var inj = new Injector([
135+
bind(Engine).toClass(Engine),
136+
bind("engine!").toAlias(Engine)
137+
]);
138+
```
139+
which implies `inj.get(Engine) === inj.get("engine!")`.
140+
131141
Note that tokens and factory functions are decoupled.
132142

133143
```

modules/angular2/src/di/binding.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,15 @@ export class BindingBuilder {
6060
);
6161
}
6262

63+
toAlias(aliasToken):Binding {
64+
return new Binding(
65+
Key.get(this.token),
66+
(aliasInstance) => aliasInstance,
67+
[new Dependency(Key.get(aliasToken), false, false, [])],
68+
false
69+
);
70+
}
71+
6372
toFactory(factoryFunction:Function, dependencies:List = null):Binding {
6473
return new Binding(
6574
Key.get(this.token),

modules/angular2/test/di/injector_spec.js

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,26 @@ export function main() {
128128
expect(car.engine).toBeAnInstanceOf(Engine);
129129
});
130130

131+
it('should bind to an alias', function() {
132+
var injector = new Injector([
133+
Engine,
134+
bind(SportsCar).toClass(SportsCar),
135+
bind(Car).toAlias(SportsCar)
136+
]);
137+
138+
var car = injector.get(Car);
139+
var sportsCar = injector.get(SportsCar);
140+
expect(car).toBeAnInstanceOf(SportsCar);
141+
expect(car).toBe(sportsCar);
142+
});
143+
144+
it('should throw when the aliased binding does not exist', function () {
145+
var injector = new Injector([
146+
bind('car').toAlias(SportsCar)
147+
]);
148+
expect(() => injector.get('car')).toThrowError('No provider for SportsCar! (car -> SportsCar)');
149+
});
150+
131151
it('should support overriding factory dependencies', function () {
132152
var injector = new Injector([
133153
Engine,
@@ -324,4 +344,4 @@ export function main() {
324344
});
325345
});
326346
});
327-
}
347+
}

0 commit comments

Comments
 (0)