注:此文仅记录博主初次学习nestjs之后的认识和理解,经验尚浅,文章内容仅供参考,如若有误,敬请指正。
控制反转IOC
此文对控制反转不做过多理论性的探讨。
- 基本理解:可以看作为工厂模式的升华,能够解开对象引用与对象创建之间的耦合。
- 实现方式:通过在全局维护一个IOC容器,来统一管理对象的配置和创建(依赖注入)。
IOC创建对象案例
1.定义一个provider类(cats.service.ts)
普通provider,注入时等同于 new CatsService(httpClient)
import { Injectable } from '@nestjs/common';
@Injectable()
export class CatsService {constructor(private readonly httpClient: HttpClientClass) {}test(): String {return 'test provider1';}
}
泛型Provider,注入时等同于 new DogsService< HttpClientClass>(httpClient)
- 基于构造函数的注入
import { Injectable } from '@nestjs/common';
// 2.多级provider = new DogsService(HttpClientClass1)
@Injectable()
export class DogsService<T>{constructor(//@Optional() 可选注入@Optional() @Inject('HTTP_OPTIONS') private readonly httpClient: T) {}test(): String {return 'test provider2';}
}
- 基于属性的注入
import { Injectable } from '@nestjs/common';
@Injectable()
export class DogsService<T>{@Inject('HTTP_OPTIONS') private readonly httpClient: T;test(): String {return 'test provider2';}
}
2.将该provider类注册至IOC容器中(app.module.ts)
import { Module } from '@nestjs/common';
import { CatsController } from './cats/cats.controller';
import { CatsService } from './cats/cats.service';@Module({controllers: [CatsController],providers: [CatsService],
})
export class AppModule {}
3.从IOC容器中获取该provider类对象(cats.controller.ts)
import { Controller, Get, Post, Body } from '@nestjs/common';
import { CatsService } from './cats.service';@Controller('cats')
export class CatsController {// provider可通过`constructor` **注入**依赖关系constructor(private catsService: CatsService) {}@Post()async test() {this.catsService.test();}}