Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Service Bus multiple QueueClients

What is the best practice for creating multiple queueclients for listening to different service bus queues? There is a MessagingFactory class however Microsoft.ServiceBus.Messaging not seems to be available as a nuget package anymore (.net core console application).

Considering QueueClient as static object what would be the recommended pattern to create multiple queueclients from a singleton host process?

Appreciate the feedback.

like image 493
Faizal Avatar asked Feb 11 '26 15:02

Faizal


2 Answers

For .net core applications, you can make use of Microsoft.Azure.ServiceBus instead of Microsoft.ServiceBus.Messaging nuget. As this is build over .net standard, this can be used in both framework and core applications. Methods and classes similar to Microsoft.ServiceBus.Messaging are available under this. Check here for samples.

like image 103
Arunprabhu Avatar answered Feb 15 '26 06:02

Arunprabhu


Able to get it working however could not use dependency injection. Any suggestions on improving this implementation would be much appreciated.

Startup.cs

// Hosted services services.AddSingleton();

ServiceBusListener.cs

    public class ServiceBusListener : BackgroundService, IServiceBusListener
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Console.WriteLine($"ServiceBusListener is starting.");

            Dictionary<string, QueueClient> queueClients = new Dictionary<string, QueueClient>();

            foreach (var queue in _svcBusSettings.Queues)
            {
                var svcBusQueueClient = new ServiceBusQueueClient(queue.Value, queue.Key);
                queueClients.Add(queue.Key, svcBusQueueClient.QueueClient);
            }   
        }
    }

ServiceBusQueueClient.cs

    public class ServiceBusQueueClient : IServiceBusQueueClient
    {
        private IQueueClient _queueClient;

        public QueueClient QueueClient
        {
            get { return _queueClient as QueueClient; }
        }

        public ServiceBusQueueClient(string serviceBusConnection, string queueName)
        {
            _queueClient = new QueueClient(serviceBusConnection, queueName);
            RegisterOnMessageHandlerAndReceiveMessages();
        }
    }
like image 24
Faizal Avatar answered Feb 15 '26 05:02

Faizal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!