JS back-end framework Nest.js Getting Started Chapter Inversion of Control IOC, Provider (2)

Note: This article only records the blogger's knowledge and understanding after learning nestjs for the first time. The experience is still shallow. The content of the article is for reference only. Please correct me if there is any error.

Inversion of Control IOC

This article does not do too much theoretical discussion on inversion of control.

  • Basic understanding: It can be seen as a sublimation of the factory model, which can uncouple the object reference and object creation.
  • Implementation method: By maintaining an IOC container globally, the configuration and creation of objects are managed uniformly (dependency injection).

IOC creation object case

1. Define a provider class (cats.service.ts)

Ordinary provider, equivalent to new CatsService(httpClient) when injected
import {
    
     Injectable } from '@nestjs/common';
@Injectable()
export class CatsService {
    
    
 constructor(
   private readonly httpClient: HttpClientClass
  ) {
    
    }
  test(): String {
    
    
    return 'test provider1';
  }
}
Generic Provider, equivalent to new DogsService< HttpClientClass>(httpClient) when injected
  • Constructor-based injection
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';
  }
}
  • Attribute-based injection
import {
    
     Injectable } from '@nestjs/common';
@Injectable()
export class DogsService<T>{
    
    
  @Inject('HTTP_OPTIONS') 
  private readonly httpClient: T;
  test(): String {
    
    
    return 'test provider2';
  }
}

2. Register the provider class to the IOC container (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. Obtain the provider class object (cats.controller.ts) from the IOC container

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();
  }

}

Guess you like

Origin blog.csdn.net/jw2268136570/article/details/107834581