Angular依赖注入框架injector的学习笔记

348 阅读1分钟

injector

An object in the Angular dependency-injection system that can find a named dependency in its cache or create a dependency using a configured provider. Injectors are created for NgModules automatically as part of the bootstrap process and are inherited through the component hierarchy.

Injector是Angular DI系统里的一种对象,可以在其内部cache里查找并返回命名的依赖,或者使用配置的provider创建新依赖。

在NgModule bootstrap过程中,injector自动被创建,并且可以在整个Component层级结构中被继承。

injector provides a singleton instance of a dependency, and can inject this same instance in multiple components.

injector维护同一种依赖的单一实例,并可将该单一实例注入多个Component中。

下面是一个例子,Angular injector根据metadata,生成被注入的实例:

@Injectable()
class UsefulService {
}

@Injectable()
class NeedsService {
  constructor(public service: UsefulService) {}
}

const injector = Injector.create({
  providers:
      [{provide: NeedsService, deps: [UsefulService]}, {provide: UsefulService, deps: []}]
});
expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true);