【问题标题】:Understanding Inject, Injectable and InjectRepository in nest了解 Nest 中的 Inject、Injectable 和 InjectRepository
【发布时间】:2020-11-22 02:59:48
【问题描述】:

我来自非打字稿和非嵌套背景。我在查看代码时发现了这段代码sn-p

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>,
  ) {}

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

对于来自不同编程语言背景的人来说,它 得知在 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:

那么,如果我们这样做@Injectable(),它的作用域是什么?

谁能解释一下@Injectable() @Inject(AreaService) @InjectRepository(Office) 之间的区别以及何时应该使用哪一个?

【问题讨论】:

    标签: typescript nestjs


    【解决方案1】:

    我知道这有点旧,但对于其他人来说:

    @InjectRepository() 上的未回答点来自 @nestjs/typeorm 包,这是一个存储库模式,可在请求范围内通过 db 连接获得,这意味着您可以找到办公室,根据您在服务提供商中的请求,查找所有 Office、创建 Office、更新 Office 或删除 Office。这是参考Nest.js

    此模块使用 forFeature() 方法来定义哪些存储库 在当前范围内注册。有了它,我们可以注入 使用 UsersRepository 到 UsersService @InjectRepository() 装饰器:

    还有您从 Nest.js 引用的段落:您的请求由您的控制器处理,因此您可以控制请求可用的内容和注入的内容。

    【讨论】:

      【解决方案2】:

      @Injectable() 就是这样做的

      在cats.service.ts 中,@Injectable() 装饰器将CatsService 类声明为可以由Nest IoC 容器管理的类。

      https://docs.nestjs.com/fundamentals/custom-providers#di-fundamentals

      它声明了一个由 Nest 识别的类,以供将来通过 @Inject(TokenName) 执行的依赖注入。

      【讨论】:

        【解决方案3】:

        回答您关于REQUEST-scope 的问题:

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

        这意味着对于由依赖于CatsServiceController 处理的每个请求,将创建一个新的CatsService 实例。这也意味着任何其他依赖于CatService 的服务/控制器将变为REQUEST-范围,即使它们是使用默认(即单例)范围定义的。记住这一点很重要,因为它可能会对您的应用产生影响,请参阅 thisthat 了解更多信息。

        【讨论】:

        • 非常好的点!也感谢有用的链接!
        猜你喜欢
        • 2016-10-22
        • 2018-05-18
        • 1970-01-01
        • 2016-09-15
        • 2020-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多