了解 Nest 中的 Inject、Injectable 和 InjectRepository

iRo*_*tia 12 typescript nestjs

我来自非打字稿和非巢背景。我正在检查代码,发现了这段代码片段

import { Inject, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { AreaService } from '../area/-area.service';
import { Repository } from 'typeorm';
import { Office } from './office.entity';
import { OfficeInterface } from './office.interface';

@Injectable()
export class OfficeService {
  constructor(
    @Inject(AreaService)
    private readonly AreaService: AreaService,
    @InjectRepository(Office)
    private readonly OfficeRepository: Repository<Office>,
  ) {}
Run Code Online (Sandbox Code Playgroud)

老实说,现在这对我来说是压倒性的。我去了Nest JS 页面来了解这一点以及他们所说的

对于来自不同编程语言背景的人来说,可能会意外地发现,在 Nest 中,几乎所有内容都在传入请求之间共享。我们有一个到数据库的连接池、具有全局状态的单例服务等。请记住,Node.js 不遵循请求/响应多线程无状态模型,在该模型中,每个请求都由单独的线程处理。因此,使用单例实例对于我们的应用程序来说是完全安全的

他们在上面的声明中是否意味着他们将所有内容添加到请求对象中nestJS

import { Injectable, Scope } from '@nestjs/common';

@Injectable({ scope: Scope.REQUEST })
export class CatsService {}

Specify injection scope by passing the scope property to the @Injectable() decorator options object:
Run Code Online (Sandbox Code Playgroud)

那么如果我们这样做的话,@Injectable()它的范围会是怎样呢?

有人可以解释一下@Injectable() @Inject(AreaService) @InjectRepository(Office)之间的区别吗?应该使用哪一个?

eol*_*eol 6

要回答有关 -scope 的问题REQUEST

@Injectable({ scope: Scope.REQUEST })
export class CatsService {}
Run Code Online (Sandbox Code Playgroud)

这意味着对于由 处理的每个请求,将创建Controller依赖于CatsService新实例的。CatsService这也意味着依赖的任何其他服务/控制器都CatService将成为REQUEST范围,即使它们是使用默认(即单例)范围定义的。这是一件需要记住的重要事情,因为它可能会对您的应用程序产生影响,请参阅以获取更多信息。