parent
a80105f30a
commit
0c4fbfc8e2
|
@ -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.
|
||||
|
||||
```
|
||||
|
|
|
@ -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),
|
||||
|
|
|
@ -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,
|
||||
|
|
Loading…
Reference in New Issue