c# - 如何将具有不同配置的第二个 eventhub 客户端注入(inject)到我的 Azure Functions 中?

标签 c# azure-functions azure-eventhub

我们在 Azure 函数中使用事件中心来发送消息,只要所有函数都使用相同的事件中心,就可以正常工作,然后我们在startup.cs中注入(inject)如下

.AddSingleton(_ => new EventHubProducerClient(config["EventHubConnectionString"], config["EventHubName"]))

然后我们将其注入(inject)到我们的函数中,如下所示:

  private readonly AuthService _authService;
        private readonly ItemService _itemService;
        private readonly PromoService _promoService;
        private readonly UserService _userService;

        private readonly EventHubProducerClient _eventHubClient;

        public BarCodeScanV4(AuthService authService, ItemService itemService, PromoService promoService, UserService userService, EventHubProducerClient eventHubClient)
        {
            _authService = authService ?? throw new ArgumentNullException(nameof(authService));
            _itemService = itemService ?? throw new ArgumentNullException(nameof(itemService));
            _promoService = promoService ?? throw new ArgumentNullException(nameof(promoService));
            _userService = userService ?? throw new ArgumentNullException(nameof(userService));
            _eventHubClient = eventHubClient ?? throw new ArgumentNullException(nameof(eventHubClient));
        }

但现在我需要注入(inject)具有不同配置的第二个 eventhub 客户端,即同一 eventhub 命名空间中的不同 eventhub 名称,但我不知道如何执行此操作

我怎样才能做到

  1. 在每个功能级别更改 eventhub 客户端的配置或
  2. 使用不同的 eventhubname 注入(inject)第二个客户端

最佳答案

我认为这只是一个 DI 问题。一个简单的解决方案是将两个 EventHubProducerClient 包装在包装器中 这是一些伪代码

public interface IWrapper{
    EventHubProducerClient GetClient1();
    EventHubProducerClient GetClient2();
}

public class Wrapper : IWrapper{
    private EventHubProducerClient client1;
    private EventHubProducerClient client2;

    public Wrapper(config1, config2){
        //Create client1 and 2
    }

    EventHubProducerClient GetClient1() => return client1
    EventHubProducerClient GetClient2() => return client2
}

然后注册DI时

AddSingelton(_ => new Wrapper(conf1, conf2))

这只是一种方法,但还有很多方法。以下是您可能会发现有用的其他一些资源。 https://andrewlock.net/using-multiple-instances-of-strongly-typed-settings-with-named-options-in-net-core-2-x/ How to register multiple implementations of the same interface in Asp.Net Core? https://devkimchi.com/2020/07/01/5-ways-injecting-multiple-instances-of-same-interface-on-aspnet-core/

关于c# - 如何将具有不同配置的第二个 eventhub 客户端注入(inject)到我的 Azure Functions 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67931131/

相关文章:

c# - 如何强制脚本在特定位置执行?

c# - Azure函数输出API调用第三方服务

azure - 是否可以从azure事件中心查询历史数据?

c# - 基本扩展器样式,覆盖标题颜色

c# - 使用 LINQ-to-SQL 从 SQL Server 存储过程返回单行值

Java vs C# 多线程性能,为什么 Java 变慢了? (包括图表和完整代码)

Azure Function 和永久进程

azure - Azure Key Vault 是否可以与函数一起使用来存储队列触发器的连接字符串?

python-3.x - Azure 组合器函数,用于使用 Python 接收数据并将其写入 Azure Blob 存储

azure 函数 - 当 eventhub 中的新事件时触发,将其写入 cosmos db - 不起作用,为什么?