Search code examples
c#azureservicebusbackground-service

Multiple Background Workers with different azure bus subscriptions


I have created a worker that can read azure bus service subscription, following examples on line. But can't find a way to have multiple workers in the same app that would read different subscriptions and do different things.

To create my app I have added the following to my Program.cs

services.AddSingleton<ISubscriptionClient>(x =>
                        new SubscriptionClient(Configuration["ServiceBus:ConnectionString"],
                                                Configuration["ServiceBus:TopicName"],
                                                Configuration["ServiceBus:SubscriptionName"]));

and in my worker:

private readonly ISubscriptionClient _subscriptionClient;

inside ExecuteAsync

_subscriptionClient.RegisterMessageHandler(async (message, token) => 
        { //do stuff }

Is there a way i can have each background worker use a different subscription?


Solution

  • Instead of injecting ISubscriptionClient as Singleton (do not recommend service resolver in this case because it won't solve your problem exactly), you can create readonly Global Variables in your worker role like below:

    private readonly ISubscriptionClient _subscriptionClient1 = new SubscriptionClient(Configuration["ServiceBus:ConnectionString1"],
                                                    Configuration["ServiceBus:TopicName1"],
                                                 Configuration["ServiceBus:SubscriptionName1"]));
    
    private readonly ISubscriptionClient _subscriptionClient2 = new SubscriptionClient(Configuration["ServiceBus:ConnectionString2"],
                                                    Configuration["ServiceBus:TopicName2"],
                                                    Configuration["ServiceBus:SubscriptionName2"]))
    

    And then, use them inside ExecutionAsync:

    _subscriptionClient1.RegisterMessageHandler(async (message, token) => 
            { //do stuff }
    _subscriptionClient2.RegisterMessageHandler(async (message, token) => 
            { //do stuff }