Search code examples
c#azureservicebus.net-standard

How to create MessageReceiver on subscription using Microsoft.Azure.ServiceBus


I'm trying to replace the .NET Framework NuGet package WindowsAzure.ServiceBus with .NET Standard Microsoft.Azure.ServiceBus and I faced the problem. How to create an instance of MessageReceiver for Service Bus topic subscription? I can create it for a queue with the code:

var receiver = new MessageReceiver(connectionString, queueName);
var bytes = receiver.ReceiveAsync().Result.Body;
string s = Encoding.UTF8.GetString(bytes);
Console.WriteLine(s);

but the MessageReceiver does not have a constructor for getting data from a Service Bus topic subscription.


Solution

  • I found the answer in the Microsoft.Azure.ServiceBus source code. It turned out that there are static functions in EntityNameHelper class that generate messaging entity paths. For example, for a subscription, it looks like

    EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName)
    

    So, full MessageReceiver initialization code looks like:

    string path = EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName);
    var receiver = new MessageReceiver(connectionString, path);
    var bytes = receiver.ReceiveAsync().Result.Body;
    string s = Encoding.UTF8.GetString(bytes);
    Console.WriteLine(s);