Matt Douhan
Matt Douhan

Reputation: 733

How can I inject a second eventhub client with different config into my Azure Function?

We are using event hubs in our Azure Functions to send messages and this works fine as long as all functions uses the same event hub, then we inject is as follows in startup.cs

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

Then we inject this into our functions as follows:

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

But now I have the need toinject a second eventhub client with a different confoguration, i.e a different eventhubname in the same eventhubnamespace but I cannot figure out how to do this

How can I either

  1. Change the configuration of my eventhub client on a per function level or
  2. Inject a second client with the different eventhubname

Upvotes: 3

Views: 1281

Answers (1)

Bjorne
Bjorne

Reputation: 1484

This is just a DI problem I believe. A simple solution would be to wrap your two EventHubProducerClient in a wrapper Here is some psudo code

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
}

Then when registering DI

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

This is just one approach but there are many. Here are some other resources you may find usefull. 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/

Upvotes: 3

Related Questions