nestjs 依赖注入方面的 “Bug” | custom providers

本文探讨了在NestJS框架中遇到的依赖注入问题,通过分析两个不同场景——场景一和场景二,揭示了问题的本质。作者指出,这些问题并非NestJS的bug,而是需要正确理解和使用自定义提供者。详细解决方案可参考NestJS官方文档,该文档详细介绍了如何在NestJS中创建和使用自定义提供者。

场景一

写法一:

export class InfrastructureStackService {
  constructor(
    private manager: InfrastructureStackManager = InfrastructureStackManager.PULUMI
  ) {}
}

写法二:

export class InfrastructureStackService {
  private manager: InfrastructureStackManager =
    InfrastructureStackManager.PULUMI;

  constructor() {}
}

场景二


@Injectable()
export class SqsService {
  private client: SQSClient;
  private queueUrl: string;

  constructor(params: {queueUrl: string}) {
    this.client = new SQSClient({
      region: AwsConfig.getRegion(), // region is required for SQS service.
    });

    this.queueUrl = params.queueUrl.toString();
  }

}
[9:15:20 AM] Found 0 errors. Watching for file changes.

[Nest] 96503  - 09/12/2022, 9:15:25 AM     LOG [NestFactory] Starting Nest application...
[Nest] 96503  - 09/12/2022, 9:15:25 AM     LOG [InstanceLoader] PrismaModule dependencies initialized +82ms
[Nest] 96503  - 09/12/2022, 9:15:25 AM   ERROR [ExceptionHandler] Nest can't resolve dependencies of the SqsService (?). Please make sure that the argument Object at index [0] is available in the AwsModule context.

Potential solutions:
- If Object is a provider, is it part of the current AwsModule?
- If Object is exported from a separate @Module, is that module imported within AwsModule?
  @Module({
    imports: [ /* the Module containing Object */ ]
  })

最终答案在这里 Documentation | NestJS - A progressive Node.js frameworkNest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reactive Programming).https://docs.nestjs.com/fundamentals/custom-providers

这并不是 Nestjs 的 bug。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值