【问题标题】:With nest.js, how can I inject a Provider that has a constructor?使用nest.js,如何注入具有构造函数的Provider?
【发布时间】:2020-08-24 08:40:48
【问题描述】:

我有 conversations.module.ts 有:

@Module({
  imports: [ImageModule, YoutubeModule],
  controllers: [ConversationsController],
  providers: [ConversationsService, ParticipantsService, StreamsService]
})
export class ConversationsModule { }

在我的conversations.controller.ts 中,我有:

@Controller('conversations')
export class ConversationsController {
    constructor(private conversationsService: ConversationsService, private imageService: ImageService, private youtubeService: YoutubeService, private participantsService: ParticipantsService, private streamsService: StreamsService) { }

但我想做的是注入 AWS S3 模块:

const secretsmanager = new S3({ region: 'us-east-1' })

这需要它被实例化。我怎样才能做到这一点?

【问题讨论】:

    标签: javascript node.js typescript dependency-injection nestjs


    【解决方案1】:

    听起来您正在寻找自定义提供程序。您可以定义一个注入令牌(一个字符串)并将其提供给一个带有键 provide 和一个键 useClassuseValueuseFactory 的对象,用于确定要注入的值。在你的情况下,你可以做类似的事情

    {
      provide: 'SECRETS_MANAGER',
      useValue: new S3({ region: 'us-east-1' }),
    }
    

    现在您可以像这样在构造函数中使用带有@Inject() 装饰器的注入令牌

    constructor(@Inject('SECRETS_MANAGER') private readonly manager: S3) {}
    

    new S3() 返回的任何类型。

    【讨论】:

    • 我在哪里做这个? module?
    • @Module()providers 数组中。这是custom provider
    猜你喜欢
    • 2021-12-23
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-01
    • 2018-03-27
    • 2018-02-25
    相关资源
    最近更新 更多