feat(di): introduce aliasing

Closes #710
Closes #747
This commit is contained in:
Pawel Kozlowski 2015-02-21 15:18:06 +01:00
parent a80105f30a
commit 0c4fbfc8e2
3 changed files with 41 additions and 2 deletions

View File

@ -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.
```

View File

@ -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),

View File

@ -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() {
});
});
});
}
}