2
votes

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.

2
QueueClient is not static in the new package. The change is that you need to manage lifecycle and connections of the objects you create rather than rely on the MessagingFactory to perform that for you.Sean Feldman
great! that works.Faizal

2 Answers

1
votes

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.

0
votes

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