Dependency Injection
Essentially, when we ask for a construct instance, we want help constructing it. A DI system can act in one of two ways when asked to resolve an instance:
- Transient mode: The dependency is always created anew
- Singleton mode: The dependency is reused
Angular only creates singletons though which means every time we ask for a dependency it will only be created once and we will be given an already existing dependency if we are not the first construct to ask for that dependency.
The default behavior of any DI framework is to use the default constructor on a class and create an instance from a class. If that class has dependencies, then it has to resolve those first. Imagine we have the following case:
export class Logger { }
export class Service {
constructor(logger: Logger) { }
}
The DI framework would crawl the chain of dependencies, find the construct that does not have any dependencies, and instantiate that first. Then it would crawl upwards and finally resolve the construct you asked for. So with this code:
import { Service } from './service';
export class ExampleComponent {
constructor(srv: Service) { }
}
The DI framework would:
- Instantiate the logger first
- Instantiate the service second
- Instantiate the component third