Yuriy Gavrishov
Yuriy Gavrishov

Reputation: 5021

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.

Upvotes: 1

Views: 3727

Answers (2)

schil227
schil227

Reputation: 312

In addition to Yuriy's excellent answer, ServieBusConnectionStringBuilder can also be used to contain the configuration data, which I find to be a little more concise.

var builder = new ServiceBusConnectionStringBuilder(connectionString)
    {
        TransportType = TransportType.AmqpWebSockets,
        EntityPath = EntityNameHelper.FormatSubscriptionPath(topic, subscription)
    };

var messageReceiver = new MessageReceiver(builder);     

Upvotes: 0

Yuriy Gavrishov
Yuriy Gavrishov

Reputation: 5021

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);

Upvotes: 7

Related Questions