Home > other >  Issue (maybe) with the code for putting message on the queue
Issue (maybe) with the code for putting message on the queue

Time:06-18

I have this code to put message on the queue

 public class AzureQueueService : IAzureQueueService
    {
        private readonly IConfiguration _config;
        private static string azureServiceBusString = null;

        public AzureQueueService(IConfiguration config)
        {
            _config = config;
            azureServiceBusString = "connString";
        }

        public async Task SendMessageAsync<T>(T serviceBusMessage, string queueName)
        {
            // since ServiceBusClient implements IAsyncDisposable we create it with "await using"
            await using var queueClient = new ServiceBusClient(azureServiceBusString);

            // create the sender
            ServiceBusSender sender = queueClient.CreateSender(queueName);

            string messageBody = JsonSerializer.Serialize(serviceBusMessage);
            var message = new ServiceBusMessage(Encoding.UTF8.GetBytes(messageBody));

            // send the message
            await sender.SendMessageAsync(message);
        }
    }

In my startup file I am doing this

services.AddTransient<IAzureQueueService, Core.Services.AzureQueueService>();

And I am using it like this

var queue = new AzureQueueService(config);
await queue.SendMessageAsync(message, "emailqueue");

Could this lead to memory leakage? I mean should I instantiate the ServiceBusClient in the constructor?

CodePudding user response:

Yes, I'd be looking to set up dependency injection for the ServiceBusClient. As per the docs here (for 7.8.x)

The ServiceBusClient, senders, receivers, and processors are safe to cache and use as a singleton for the lifetime of the application, which is best practice when messages are being sent or received regularly. They are responsible for efficient management of network, CPU, and memory use, working to keep usage low during periods of inactivity.

Also, see Best Practises for performance improvements using Service Bus Messaging

  • Related