2015-07-29 19:32:42 -04:00
# Dependency Injection (DI): Documentation (Advanced Topics)
This document talks about advanced topics related to the DI module and how it is used in Angular. You don't have to know this to use DI in Angular or independently.
### Key
Most of the time we do not have to deal with keys.
```
var inj = Injector.resolveAndCreate([
bind(Engine).toFactory(() => new TurboEngine()) //the passed in token Engine gets mapped to a key
]);
var engine = inj.get(Engine); //the passed in token Engine gets mapped to a key
```
Now, the same example, but with keys.
```
var ENGINE_KEY = Key.get(Engine);
var inj = Injector.resolveAndCreate([
bind(ENGINE_KEY).toFactory(() => new TurboEngine()) // no mapping
]);
var engine = inj.get(ENGINE_KEY); // no mapping
```
2016-03-21 06:57:17 -04:00
Every key has an id, which we utilize to store providers and instances. So Injector uses keys internally for performance reasons.
2015-07-29 19:32:42 -04:00
### ProtoInjector and Injector
2017-01-27 01:30:42 -05:00
Often there is a need to create multiple instances of essentially the same injector. In Angular, for example, every component element type gets an injector configured in the same way.
2015-07-29 19:32:42 -04:00
Doing the following would be very inefficient.
```
2016-03-21 06:57:17 -04:00
function createComponetInjector(parent, providers: Binding[]) {
return parent.resolveAndCreateChild(providers);
2015-07-29 19:32:42 -04:00
}
```
2016-03-21 06:57:17 -04:00
This would require us to resolve and store providers for every single component instance. Instead, we want to resolve and store the providers for every component type, and create a set of instances for every component. To enable that DI separates the meta information about injectables (providers and their dependencies), which are stored in `ProtoInjector` , and injectables themselves, which are stored in `Injector` .
2015-07-29 19:32:42 -04:00
```
2016-03-21 06:57:17 -04:00
var proto = new ProtoInjector(providers); // done once
2015-07-29 19:32:42 -04:00
function createComponentInjector(parent, proto) {
return new Injector(proto, parent);
}
```
`Injector.resolveAndCreate` creates both a `ProtoInjector` and an `Injector` .
### Host & Visibility
An injector can have a parent. The parent relationship can be marked as a "host" as follows:
```
var child = new Injector(proto, parent, true /* host */);
```
Hosts are used to constraint dependency resolution. For instance, in the following example, DI will stop looking for `Engine` after reaching the host.
```
class Car {
constructor(@Host() e: Engine) {}
}
```
Imagine the following scenario:
```
ParentInjector
/ \
2015-08-12 19:34:13 -04:00
/ \ host
2015-07-29 19:32:42 -04:00
Child1 Child2
```
2016-03-21 06:57:17 -04:00
Here both Child1 and Child2 are children of ParentInjector. Child2 marks this relationship as host. ParentInjector might want to expose two different sets of providers for its "regular" children and its "host" children. providers visible to "regular" children are called "public" and providers visible to "host" children are called "private". This is an advanced use case used by Angular, where components can provide different sets of providers for their children and their view.
2015-07-29 19:32:42 -04:00
Let's look at this example.
```
class Car {
constructor(@Host() e: Engine) {}
}
var parentProto = new ProtoInjector([
2015-08-12 19:34:13 -04:00
new BindingWithVisibility(Engine, Visibility.Public),
new BindingWithVisibility(Car, Visibility.Public)
2015-07-29 19:32:42 -04:00
]);
var parent = new Injector(parentProto);
2015-08-12 19:34:13 -04:00
var hostChildProto = new ProtoInjector([new BindingWithVisibility(Car, Visibility.Public)]);
2015-07-29 19:32:42 -04:00
var hostChild = new Injector(hostChildProto, parent, true);
2015-08-12 19:34:13 -04:00
var regularChildProto = new ProtoInjector([new BindingWithVisibility(Car, Visibility.Public)]);
2015-07-29 19:32:42 -04:00
var regularChild = new Injector(regularChildProto, parent, false);
2015-08-12 19:34:13 -04:00
hostChild.get(Car); // will throw because public dependencies declared at the host cannot be seen by child injectors
2015-07-29 19:32:42 -04:00
parent.get(Car); // this works
regularChild.get(Car); // this works
```
2015-08-12 19:34:13 -04:00
Now, let's mark `Engine` as private:
2015-07-29 19:32:42 -04:00
```
class Car {
constructor(@Host() e: Engine) {}
}
var parentProto = new ProtoInjector([
2015-08-12 19:34:13 -04:00
new BindingWithVisibility(Engine, Visibility.Private),
new BindingWithVisibility(Car, Visibility.Public)
2015-07-29 19:32:42 -04:00
]);
var parent = new Injector(parentProto);
2015-08-12 19:34:13 -04:00
var hostChildProto = new ProtoInjector([new BindingWithVisibility(Car, Visibility.Public)]);
2015-07-29 19:32:42 -04:00
var hostChild = new Injector(hostChildProto, parent, true);
2015-08-12 19:34:13 -04:00
var regularChildProto = new ProtoInjector([new BindingWithVisibility(Car, Visibility.Public)]);
2015-07-29 19:32:42 -04:00
var regularChild = new Injector(regularChildProto, parent, false);
hostChild.get(Car); // this works
parent.get(Car); // this throws
regularChild.get(Car); // this throws
```
2015-08-12 19:34:13 -04:00
Now, let's mark `Engine` as both public and private:
2015-07-29 19:32:42 -04:00
```
class Car {
constructor(@Host() e: Engine) {}
}
var parentProto = new ProtoInjector([
2015-08-12 19:34:13 -04:00
new BindingWithVisibility(Engine, Visibility.PublicAndPrivate),
new BindingWithVisibility(Car, Visibility.Public)
2015-07-29 19:32:42 -04:00
]);
var parent = new Injector(parentProto);
2015-08-12 19:34:13 -04:00
var hostChildProto = new ProtoInjector([new BindingWithVisibility(Car, Visibility.Public)]);
2015-07-29 19:32:42 -04:00
var hostChild = new Injector(hostChildProto, parent, true);
2015-08-12 19:34:13 -04:00
var regularChildProto = new ProtoInjector([new BindingWithVisibility(Car, Visibility.Public)]);
2015-07-29 19:32:42 -04:00
var regularChild = new Injector(regularChildProto, parent, false);
hostChild.get(Car); // this works
parent.get(Car); // this works
regularChild.get(Car); // this works
```
2017-01-27 01:30:42 -05:00
## Angular and DI
2015-07-29 19:32:42 -04:00
2017-01-27 01:30:42 -05:00
Now let's see how Angular uses DI behind the scenes.
2015-07-29 19:32:42 -04:00
The right mental model is to think that every DOM element has an Injector. (In practice, only interesting elements containing directives will have an injector, but this is a performance optimization)
2016-03-21 06:57:17 -04:00
There are two properties that can be used to configure DI: providers and viewProviders.
2015-07-29 19:32:42 -04:00
2016-03-21 06:57:17 -04:00
- `providers` affects the element and its children.
- `viewProviders` affects the component's view.
2015-07-29 19:32:42 -04:00
2016-03-21 06:57:17 -04:00
Every directive can declare injectables via `providers` , but only components can declare `viewProviders` .
2015-07-29 19:32:42 -04:00
Let's look at a complex example that shows how the injector tree gets created.
```
< my-component my-directive >
2015-08-12 19:34:13 -04:00
< needs-service > < / needs-service >
2015-07-29 19:32:42 -04:00
< / my-component >
```
2015-08-12 19:34:13 -04:00
Both `MyComponent` and `MyDirective` are created on the same element.
2015-07-29 19:32:42 -04:00
```
@Component ({
2015-08-12 19:34:13 -04:00
selector: 'my-component',
2016-03-21 06:57:17 -04:00
providers: [
2015-08-12 19:34:13 -04:00
bind('componentService').toValue('Host_MyComponentService')
],
2016-03-21 06:57:17 -04:00
viewProviders: [
2015-08-12 19:34:13 -04:00
bind('viewService').toValue('View_MyComponentService')
2016-03-08 16:36:48 -05:00
],
2015-07-29 19:32:42 -04:00
template: `<needs-view-service></needs-view-service>` ,
directives: [NeedsViewService]
})
class MyComponent {}
@Directive ({
selector: '[my-directive]',
2016-03-21 06:57:17 -04:00
providers: [
2015-08-12 19:34:13 -04:00
bind('directiveService').toValue('MyDirectiveService')
2015-07-29 19:32:42 -04:00
]
})
class MyDirective {
}
```
2015-08-12 19:34:13 -04:00
`NeedsService` and `NeedsViewService` look like this:
2015-07-29 19:32:42 -04:00
```
@Directive ({
selector: 'needs-view-service'
})
class NeedsViewService {
constructor(@Host() @Inject ('viewService') viewService) {}
}
@Directive ({
selector: 'needs-service'
})
class NeedsService {
constructor(@Host() @Inject ('componentService') service1,
@Host () @Inject ('directiveService') service2) {}
}
```
This will create the following injector tree.
```
2015-08-12 19:34:13 -04:00
Injector1 [
{binding: MyComponent, visibility: Visibility.PublicAndPrivate},
{binding: 'componentService', visibility: Visibility.PublicAndPrivate},
{binding: 'viewService', visibility: Visibility.Private},
{binding: MyDirective visibility: Visibility.Public},
{binding: 'directiveService', visibility: Visibility.Public}
]
2015-07-29 19:32:42 -04:00
/ \
| \ host
2015-08-12 19:34:13 -04:00
Injector2 [ Injector3 [
{binding: NeedsService, visibility: Visibility.Public} {binding: NeedsViewService, visibility: Visibility.Public}
] ]
2015-07-29 19:32:42 -04:00
```
2016-03-21 06:57:17 -04:00
As you can see the component and its providers can be seen by its children and its view. The view providers can be seen only by the view. And the providers of other directives can be seen only their children.
2015-07-29 19:32:42 -04:00