I have an azure function which uses service bus topic. Also I have to write messages into two service bus topics. So obviously two connection strings for the the two topics (I am using topic level connection strings).
Initially I have only one topic and I implemented the dependency injection like this
var serviceBusConnectionString = configuration.GetSection("ServiceBusConnectionString").Value;
if (string.IsNullOrEmpty(serviceBusConnectionString))
{
throw new InvalidOperationException(
"Please specify a valid ServiceBusConnectionString in the Azure Functions Settings or your local.settings.json file.");
}
//using AMQP as transport
services.AddSingleton((s) => {
return new ServiceBusClient(serviceBusConnectionString, new ServiceBusClientOptions() { TransportType = ServiceBusTransportType.AmqpWebSockets });
});
and injected it like this
private readonly ServiceBusClient _serviceBusClient;
public MessageBrokerService(ServiceBusClient serviceBusClient)
{
_serviceBusClient = serviceBusClient;
}
public async Task<Message> PushToTopic(string topic, string message)
{
Message m = new Message();
try
{
var sender = _serviceBusClient.CreateSender(topic);
var msg = new ServiceBusMessage(message);
await sender.SendMessageAsync(msg);
m.Status = Domain.Enums.Status.Success;
m.Remarks = "Message posted successfull";
}
catch (ServiceBusException ex)
{
m.Status = Domain.Enums.Status.Failure;
m.Remarks = ex.Message;
}
catch(Exception ex)
{
m.Status = Domain.Enums.Status.Failure;
m.Remarks = ex.Message;
}
m.Timestamp = "";
return m;
}
But since I have two connection strings depending on the topic the calling servicepassed into the method, how can I achieve this.
That means single client, but switch conenction string based on topic in dependency injection