Search code examples
c#azureservicebusnservicebus

Azure ServiceBus equivalent to NServiceBus.IHandleMessages, or should I have a bunch of queues instead?


So I am introducing a servicebus for our project and I wanted to use the Azure Messaging Servicebus (https://www.nuget.org/packages/Azure.Messaging.ServiceBus) library instead of NServiceBus which I am used to.

Previously when using NServiceBus I would just implement the interface IHandleMessage for each message I wanted to receive, and all was peachy.

But in Azure Servicebus I cannot find a feature like this. Instead it seems I have to create a queue per message type instead of sending multiple message-types on the same queue, and have one processor per queue... Seems like a lot of plumbing when you have about 100 different messagetypes to implement.

So maybe NServiceBus is the correct option? Or is there something I don't know here :)

Thanks in advance


Solution

  • But in Azure Servicebus I cannot find a feature like this.

    That's correct. Azure Service Bus SDK provides the means to work with the service. It is not an opinionated middleware. NServiceBus is middleware. It leverages the Azure Service Bus SDK as a foundation to provide messaging abstractions that are not specific to any given messaging service, such as Azure Service Bus. A handler per message type is a middleware feature. You could implement it by having a header representing the logical message type. Your receiving code would have to deserialize the payload to the given message type, create an appropriate handler class, and pass the object representing the message to the handler instance. That's what NServiceBus and similar middleware tools are doing at an elementary level.

    A more naive version would be to have a message handler, looking at the logical message type header, and invoking an appropriate method, passing in appropriately deserialized object.

    If you're using ServiceBusMessageProcessor, here's a pseudo-code to demonstrate the naive approach. I'm assuming messages serialized as JSON.

    var processor = client.CreateProcessor("input.queue", new ServiceBusProcessorOptions());
    processor.ProcessMessageAsync += MessageHandler;
    
    async Task MessageHandler(ProcessMessageEventArgs args)
    {
        var messageType = args.Message.ApplicationProperties["message-type"];
        switch(messageType)
        {
            case "MessageX": 
                HandleX(args.Message.Body.ToObjectFromJson<MessageX>());
                break;
            case "MessageY": 
                HandleY(args.Message.Body.ToObjectFromJson<MessageY>());
                break;
            default: 
                thrown new Exception($"No handler was found for message of type '{messageType}'");
        }
        await args.CompleteMessageAsync(args.Message);
    }