Search code examples
signalrservicebusazureservicebus

How can I use SignalR as Azure Service Bus transport?


I'm trying to find an alternative to using REST to read Azure Service Bus Topic Subscriptions from the browser. Seems like SignalR would be a natural for this but I can't seem to find anyone that has done it. I'm not talking about scale-out, just a SignalR Hub that would relay a set of Service Bus functions back and forth to the browser. I'm thinking of functions like,

addReceiver(string topic, string subscriptionID);
defineSubscription(string name, string subscriptionRule);
deleteSubscription(string name);
postMessageToTopic(string topic, string message);

addReceiver would initiate an async receive on the subscription. Each time a message came available from Service Bus, a function would be called on the JS client.


Solution

  • Here's some code to point people in the right direction.

    namespace SBTester
    {
        public class SBHub : Hub
        {
            public void AddReceiver(string topic, string subscriptionName, string subscriptionFilter)
            {
                string messageData;
    
                TopicConnector.Initialize(  topic,
                                            Context.ConnectionId + "." + subscriptionName,
                                            subscriptionFilter);
    
                // Initiate receive loop on Service Bus
                TopicConnector.SBClient.OnMessage((receivedMessage) =>
                {
                    try
                    {
                        // Process the message
                        messageData = receivedMessage.GetBody<string>();
                        Clients.Caller.onMessage(topic, messageData);
                    }
                    catch
                    {
                        // Handle any message processing specific exceptions here
                    }
                });
            }
            public void DefineSubscription(string topic, string subscriptionRule)
            {
                // Call Service Bus to create Subscription on the Specified topic
            }
            public void PostMessageToTopic(string topic, string message)
            {
                // Call Service Bus to send a message
                Clients.All.addNewMessageToPage(topic, message);
            }
    
        }
    }