1

We are trying to implement Azure service bus for managing user "Work Queues"

Background:

We have a web UI pushing new items to a Web API which are persisted to a DB and then pushed to a Service Bus Queue. All messages have a property which denote who can work on the message. For providing a user with the ability to pick messages assigned to them, I am thinking about creating a topic with subscriptions that filter on that property.

Approach

To achieve the above mentioned capability:

  • I need to register a sender for the queue and a sender for the topic all within the same Web API. I have tried adding the two senders as Singletons but during DI, how do I pick which sender to use ?
services.TryAddSingleton(implementationFactory =>
{
    var serviceBusConfiguration = implementationFactory.GetRequiredService<IMessagingServiceConfiguration>();
    var serviceBusClient = new ServiceBusClient(serviceBusConfiguration.IntakeQueueSendConnectionString);
    var serviceBusSender = serviceBusClient.CreateSender(serviceBusConfiguration.IntakeQueueName);
    return serviceBusSender;
});


services.TryAddSingleton(implementationFactory =>
{
    var serviceBusConfiguration = implementationFactory.GetRequiredService<IMessagingServiceConfiguration>();
    var serviceBusClient = new ServiceBusClient(serviceBusConfiguration.TopicConnectionString);
    var topicSender = serviceBusClient.CreateSender(serviceBusConfiguration.TopicName);
    return topicSender;
});

I am using the above setup to add the services as singletons and individually I am able to send and receive messages from either the topic or the queue.

How can I register both the implementations and pick which one should be injected when I use DI in the constructor to consume it.

Ron
  • 886
  • 13
  • 39

1 Answers1

1

With respect to resolving DI registration for multiple instances of the same type, the first answer to this question illustrates using a service resolver with ASP.NET Core. To my knowledge, that is still the best approach.

For the senders, you could differentiate by checking their EntityPath property to identify whether they point to your queue or topic.

Jesse Squire
  • 6,107
  • 1
  • 27
  • 30