官术网_书友最值得收藏!

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
主站蜘蛛池模板: 和静县| 宁城县| 文登市| 伊宁县| 兴隆县| 扬州市| 门头沟区| 辉南县| 泽普县| 正阳县| 安多县| 隆林| 天水市| 游戏| 雷波县| 邛崃市| 定南县| 宁乡县| 五莲县| 朝阳区| 新兴县| 内丘县| 铜鼓县| 庄浪县| 营山县| 罗甸县| 石嘴山市| 五寨县| 宜兴市| 清远市| 金川县| 乃东县| 青岛市| 罗山县| 弋阳县| 诸城市| 兴安盟| 任丘市| 民丰县| 南漳县| 延津县|