首页 > 解决方案 > 如何将具有不同配置的第二个 eventthub 客户端注入我的 Azure 函数?

问题描述

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

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

然后我们将它注入到我们的函数中,如下所示:

  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));
        }

但是现在我需要注入具有不同配置的第二个 eventthub 客户端,即在同一个 eventthubnamespace 中的不同 eventthubname 但我不知道如何做到这一点

我怎么能

  1. 在每个功能级别更改我的 eventthub 客户端的配置或
  2. 使用不同的 eventthubname 注入第二个客户端

标签: c#azure-functionsazure-eventhub

解决方案


我相信这只是一个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/ 如何在 Asp 中注册同一接口的多个实现。网核? https://devkimchi.com/2020/07/01/5-ways-injecting-multiple-instances-of-same-interface-on-aspnet-core/


推荐阅读