學(xué)習(xí)資料來自 Angular.cn 與 Angular.io。
依賴注入 (Dependency injection)
依賴注入簡稱為 DI,它是重要的程序設(shè)計模式。DI 可以讓類從外部源中獲得它的依賴,而不必親自創(chuàng)建它們。
為什么需要依賴注入?
示例
src/app/car/car.ts (without DI)
export class Car {
public engine: Engine;
public tires: Tires;
public description = 'No DI';
constructor() {
this.engine = new Engine();
this.tires = new Tires();
}
// Method using the engine and tires
drive() {
return `${this.description} car with ` +
`${this.engine.cylinders} cylinders and ${this.tires.make} tires.`;
}
}
這個 Car
類在構(gòu)造函數(shù)中用具體的 Engine
和 Tires
類實例化出自己的副本,它過于脆弱、缺乏彈性并且難以測試。
改進的 DI 版本示例
src/app/car/car.ts (without DI)
export class Car {
public engine: Engine;
public tires: Tires;
public description = 'DI';
constructor(public engine: Engine, public tires: Tires) { }
// Method using the engine and tires
drive() {
return `${this.description} car with ` +
`${this.engine.cylinders} cylinders and ${this.tires.make} tires.`;
}
}
使用這個 DI 版本的示例1:
// Simple car with 4 cylinders and Flintstone tires.
let car = new Car(new Engine(), new Tires());
使用這個 DI 版本的示例2:
class Engine2 {
constructor(public cylinders: number) { }
}
// Super car with 12 cylinders and Flintstone tires.
let bigCylinders = 12;
let car = new Car(new Engine2(bigCylinders), new Tires());
使用這個 DI 版本的測試:
class MockEngine extends Engine { cylinders = 8; }
class MockTires extends Tires { make = 'YokoGoodStone'; }
// Test car with 8 cylinders and YokoGoodStone tires.
let car = new Car(new MockEngine(), new MockTires());
沒有注入器 (injector) 時,使用該 DI 類的示例
src/app/car/car-factory.ts
import { Engine, Tires, Car } from './car';
// BAD pattern!
export class CarFactory {
createCar() {
let car = new Car(this.createEngine(), this.createTires());
car.description = 'Factory';
return car;
}
createEngine() {
return new Engine();
}
createTires() {
return new Tires();
}
}
應(yīng)用規(guī)模變大之后,該工廠類會變得極其復(fù)雜難以維護。
使用依賴注入框架時,注入器可以讓事情變得簡單:
let car = injector.get(Car);
說明:
Car
不需要知道如何創(chuàng)建Engine
和Tires
。 消費者不需要知道如何創(chuàng)建Car
。 開發(fā)人員不需要維護巨大的工廠類。Car
和消費者只要簡單地請求想要什么,注入器就會交付它們。
Angular 依賴注入
配置注入器
不需要創(chuàng)建 Angular 注入器。 Angular 在啟動過程中自動為我們創(chuàng)建一個應(yīng)用級注入器。
示例
src/main.ts (bootstrap)
platformBrowserDynamic().bootstrapModule(AppModule);
我們必須通過注冊提供商 (provider) 來配置注入器,這些提供商為應(yīng)用創(chuàng)建所需服務(wù)。
示例1:在 NgModule
中注冊提供商
src/app/app.module.ts
@NgModule({
imports: [
BrowserModule
],
declarations: [
AppComponent,
CarComponent,
HeroesComponent,
/* . . . */
],
providers: [
UserService,
{ provide: APP_CONFIG, useValue: HERO_DI_CONFIG }
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
示例2:在組件中注冊提供商
src/app/heroes/heroes.component.ts
import { Component } from '@angular/core';
import { HeroService } from './hero.service';
@Component({
selector: 'my-heroes',
providers: [HeroService],
template: `
<h2>Heroes</h2>
<hero-list></hero-list>
`
})
export class HeroesComponent { }
該用 NgModule 還是應(yīng)用組件來注冊提供商?
APP_CONFIG
服務(wù)需要在應(yīng)用中到處可用,所以它被注冊到 AppModule
@NgModule
的 providers
數(shù)組是合理的。
HeroService
只在英雄特性區(qū)使用,因此在 HeroesComponent
中注冊它是合理的。
根據(jù)服務(wù)使用的范圍確定提供商的合理注冊位置。
示例 HeroListComponent
從注入的 HeroService
獲取英雄數(shù)據(jù)。
src/app/heroes/hero.service.ts
import { Injectable } from '@angular/core';
import { HEROES } from './mock-heroes';
@Injectable()
export class HeroService {
getHeroes() { return HEROES; }
}
src/app/heroes/hero-list.component.ts
import { Component } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
selector: 'hero-list',
template: `
<div *ngFor="let hero of heroes">
{{hero.id}} - {{hero.name}}
</div>
`
})
export class HeroListComponent {
heroes: Hero[];
constructor(heroService: HeroService) {
this.heroes = heroService.getHeroes();
}
}
隱式注入器的創(chuàng)建
可以顯式創(chuàng)建注入器,但一般情況下使用隱式創(chuàng)建注入器。
單例服務(wù)
在一個注入器的范圍內(nèi),依賴都是單例的。 在這個例子中,HeroesComponent
和它的子組件 HeroListComponent
共享同一個 HeroService
實例。
Angular DI 是一個分層的依賴注入系統(tǒng),這意味著嵌套的注入器可以創(chuàng)建它們自己的服務(wù)實例。更多內(nèi)容見多級依賴注入器。
測試組件
示例
let expectedHeroes = [{name: 'A'}, {name: 'B'}]
let mockService = <HeroService> {getHeroes: () => expectedHeroes }
it('should have heroes when HeroListComponent created', () => {
let hlc = new HeroListComponent(mockService);
expect(hlc.heroes.length).toEqual(expectedHeroes.length);
});
更多內(nèi)容見測試。
當(dāng)服務(wù)需要別的服務(wù)時
src/app/heroes/hero.service.ts
import { Injectable } from '@angular/core';
import { HEROES } from './mock-heroes';
import { Logger } from '../logger.service';
@Injectable()
export class HeroService {
constructor(private logger: Logger) { }
getHeroes() {
this.logger.log('Getting heroes ...');
return HEROES;
}
}
為什么要用 @Injectable()?
@Injectable()
標(biāo)識一個類可以被注入器實例化。
建議:為每個服務(wù)類都添加
@Injectable()
。
為什么不標(biāo)記 HerosComponent
為 @Injectable()
呢?
我們可以添加它,但是沒有必要。因為 HerosComponent
已經(jīng)有 @Component
裝飾器了,@Component
(@Directive
以及 @Pipe
)是 Injectable 的子類型。
創(chuàng)建和注冊日志服務(wù)
示例:創(chuàng)建日志服務(wù)
src/app/logger.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class Logger {
logs: string[] = []; // capture logs for testing
log(message: string) {
this.logs.push(message);
console.log(message);
}
}
示例:注冊日志服務(wù)
src/app/app.module.ts (excerpt)
providers: [Logger]
注入器的提供商們
提供商提供依賴值的一個具體的、運行時的版本。 注入器依靠提供商創(chuàng)建服務(wù)的實例,注入器再將服務(wù)的實例注入組件或其它服務(wù)。
必須為注入器注冊一個服務(wù)的提供商,否則它不知道該如何創(chuàng)建該服務(wù)。
Provider 類和一個提供商的字面量
注冊提供商的簡寫表達(dá)式:
providers: [Logger]
等效的明細(xì)寫法為:
[{ provide: Logger, useClass: Logger }]
第一個是令牌,它作為鍵值 (key) 使用,用于定位依賴值和注冊提供商。
第二個是一個提供商定義對象。 可以把它看做是指導(dǎo)如何創(chuàng)建依賴值的配方。
備選的類提供商
可以為提供商使用不同的類:
[{ provide: Logger, useClass: BetterLogger }]
帶依賴的類提供商
示例:
@Injectable()
class EvenBetterLogger extends Logger {
constructor(private userService: UserService) { super(); }
log(message: string) {
let name = this.userService.user.name;
super.log(`Message to ${name}: ${message}`);
}
}
注冊提供商:
[ UserService,
{ provide: Logger, useClass: EvenBetterLogger }]
別名類提供商
當(dāng)舊組件想使用 OldLogger
記錄消息時,我們希望改用 NewLogger
的單例對象來記錄。不管組件請求的是新的還是舊的日志服務(wù),依賴注入器注入的都應(yīng)該是同一個單例對象。 也就是說,OldLogger
應(yīng)該是 NewLogger
的別名。
嘗試使用 useClass
會導(dǎo)致意外的后果:
[ NewLogger,
// Not aliased! Creates two instances of NewLogger
{ provide: OldLogger, useClass: NewLogger}]
正確的做法是使用 useExisting
選項指定別名:
[ NewLogger,
// Alias OldLogger w/ reference to NewLogger
{ provide: OldLogger, useExisting: NewLogger}]
值提供商
有時,提供一個預(yù)先做好的對象會比請求注入器從類中創(chuàng)建它更容易。
// An object in the shape of the logger service
let silentLogger = {
logs: ['Silent logger says "Shhhhh!". Provided via "useValue"'],
log: () => {}
};
可以通過 useValue
選項來注冊提供商,它會讓這個對象直接扮演 logger
的角色:
[{ provide: Logger, useValue: silentLogger }]
工廠提供商
有時我們需要動態(tài)創(chuàng)建這個依賴值,因為它所需要的信息直到最后一刻才能確定。 還假設(shè)這個可注入的服務(wù)沒法通過獨立的源訪問此信息。這種情況下可調(diào)用工廠提供商。
HeroService
必須對普通用戶隱藏掉秘密英雄。 只有授權(quán)用戶才能看到秘密英雄。
與 EvenBetterLogger
不同,不能把 UserService
注入到 HeroService
中。 HeroService
無權(quán)訪問用戶信息,來決定誰有授權(quán)誰沒有授權(quán)。讓 HeroService
的構(gòu)造函數(shù)帶上一個布爾型的標(biāo)志,來控制是否顯示隱藏的英雄。
示例
src/app/heroes/hero.service.ts (excerpt)
constructor(
private logger: Logger,
private isAuthorized: boolean) { }
getHeroes() {
let auth = this.isAuthorized ? 'authorized ' : 'unauthorized';
this.logger.log(`Getting heroes for ${auth} user.`);
return HEROES.filter(hero => this.isAuthorized || !hero.isSecret);
}
我們可以注入 Logger
,但是不能注入邏輯型的 isAuthorized
。 我們不得不通過工廠提供商創(chuàng)建這個 HeroService
的新實例。
示例
src/app/heroes/hero.service.provider.ts (excerpt)
let heroServiceFactory = (logger: Logger, userService: UserService) => {
return new HeroService(logger, userService.user.isAuthorized);
};
export let heroServiceProvider =
{ provide: HeroService,
useFactory: heroServiceFactory,
deps: [Logger, UserService]
};
HeroService
不能訪問 UserService
,但是工廠方法可以。
useFactory
字段告訴 Angular:這個提供商是一個工廠方法,它的實現(xiàn)是 heroServiceFactory
。
deps
屬性是提供商令牌數(shù)組。 Logger
和 UserService
類作為它們自身類提供商的令牌。 注入器解析這些令牌,把相應(yīng)的服務(wù)注入到工廠函數(shù)中相應(yīng)的參數(shù)中去。
更新后的 HeroesComponent
示例
src/app/heroes/heroes.component.ts
import { Component } from '@angular/core';
import { heroServiceProvider } from './hero.service.provider';
@Component({
selector: 'my-heroes',
template: `
<h2>Heroes</h2>
<hero-list></hero-list>
`,
providers: [heroServiceProvider]
})
export class HeroesComponent { }
依賴注入令牌
當(dāng)向注入器注冊提供商時,實際上是把這個提供商和一個 DI 令牌關(guān)聯(lián)起來了。 注入器維護一個內(nèi)部的令牌-提供商映射表,這個映射表會在請求依賴時被引用到。 令牌就是這個映射表中的鍵值。
只要定義一個 HeroService
類型的構(gòu)造函數(shù)參數(shù), Angular 就會知道把跟 HeroService
類令牌關(guān)聯(lián)的服務(wù)注入進來:
constructor(heroService: HeroService)
這是一個特殊的規(guī)約,因為大多數(shù)依賴值都是以類的形式提供的。
非類依賴
如果依賴值不是一個類呢?有時候想要注入的東西是一個字符串,函數(shù)或者對象。
示例
src/app/app-config.ts
export interface AppConfig {
apiEndpoint: string;
title: string;
}
export const HERO_DI_CONFIG: AppConfig = {
apiEndpoint: 'api.heroes.com',
title: 'Dependency Injection'
};
TypeScript 接口不是一個有效的令牌
CONFIG
常量有一個接口:AppConfig
。不幸的是,不能把 TypeScript 接口用作令牌:
// FAIL! Can't use interface as provider token
[{ provide: AppConfig, useValue: HERO_DI_CONFIG })]
// FAIL! Can't inject using the interface as the parameter type
constructor(private config: AppConfig){ }
接口只是 TypeScript 設(shè)計時 (design-time) 的概念。JavaScript 沒有接口。 TypeScript 接口不會出現(xiàn)在生成的 JavaScript 代碼中。 在運行期,沒有接口類型信息可供 Angular 查找。
InjectionToken
解決方案是為非類依賴定義和使用 InjectionToken 作為提供商令牌。
import { InjectionToken } from '@angular/core';
export let APP_CONFIG = new InjectionToken<AppConfig>('app.config');
類型參數(shù),雖然是可選的,但可以向開發(fā)者和開發(fā)工具傳達(dá)類型信息。 而且這個令牌的描述信息也可以為開發(fā)者提供幫助。
使用這個 InjectionToken
對象注冊依賴的提供商:
providers: [{ provide: APP_CONFIG, useValue: HERO_DI_CONFIG }]
這個配置對象可以注入到任何需要它的構(gòu)造函數(shù)中:
constructor(@Inject(APP_CONFIG) config: AppConfig) {
this.title = config.title;
}
雖然
AppConfig
接口在依賴注入過程中沒有任何作用,但它為該類中的配置對象提供了強類型信息。
或者在 ngModule 中提供并注入這個配置對象,如 AppModule
:
providers: [
UserService,
{ provide: APP_CONFIG, useValue: HERO_DI_CONFIG }
],
可選依賴
可以把構(gòu)造函數(shù)的參數(shù)標(biāo)記為 @Optional()
,告訴 Angular 該依賴是可選的:
import { Optional } from '@angular/core';
constructor(@Optional() private logger: Logger) {
if (this.logger) {
this.logger.log(some_message);
}
}
當(dāng)使用 @Optional()
時,代碼必須準(zhǔn)備好如何處理空值。 如果其它的代碼沒有注冊一個 logger
,注入器會設(shè)置該 logger
的值為空 null。
附錄:直接使用注入器
要避免使用此技術(shù),除非確實需要它。參見 [服務(wù)定位器模式]。(https://en.wikipedia.org/wiki/Service_locator_pattern)
附錄:為什么建議每個文件只放一個類
如果我們蔑視這個建議,并且 —— 比如說 —— 把 HeroService
和 HeroesComponent
組合在同一個文件里, 就得把組件定義放在最后面! 如果把組件定義在了服務(wù)的前面, 在運行時拋出空指針錯誤。
通過在獨立的文件中定義組件和服務(wù),可以完全避免此問題,也不會造成混淆。
總結(jié)
依賴注入是一個重要的模式,對模塊化設(shè)計以及單元測試都起到了很大的作用。
TODO: 烹飪寶典內(nèi)容待整合
C# 開發(fā)者可以閱讀 Developer's Guide to Dependency Injection Using Unity 學(xué)習(xí)了解在 C# 中使用 Unity 實現(xiàn) DI。