Azure Service Bus - topics, messages - using .NET Core Azure Service Bus - topics, messages - using .NET Core azure azure

Azure Service Bus - topics, messages - using .NET Core


The support for Azure Service Bus in .Net Core is getting better and better. There is a dedicated nuget package for it: Microsoft.Azure.ServiceBus. As for now (March 2018) it supports most of the scenarios that you might need, altough there are some gaps, like:

  • receiving messages in batches
  • checking if topic / queue / subscription exists
  • creating new topic / queue / subscription from code

As for OnMessage support for receiving messages, there is a new method: RegisterMessageHandler, that does the same thing.

Here is a code sample how it can be used:

public class MessageReceiver{    private const string ServiceBusConnectionString = "Endpoint=sb://bialecki.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=[privateKey]";    public void Receive()    {        var subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, "productRatingUpdates", "sampleSubscription");        try        {            subscriptionClient.RegisterMessageHandler(                async (message, token) =>                {                    var messageJson = Encoding.UTF8.GetString(message.Body);                    var updateMessage = JsonConvert.DeserializeObject<ProductRatingUpdateMessage>(messageJson);                    Console.WriteLine($"Received message with productId: {updateMessage.ProductId}");                    await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);                },                new MessageHandlerOptions(async args => Console.WriteLine(args.Exception))                { MaxConcurrentCalls = 1, AutoComplete = false });        }        catch (Exception e)        {            Console.WriteLine("Exception: " + e.Message);        }    }}

For full information have a look at my blog posts:

Sending messages in .Net Core: http://www.michalbialecki.com/2017/12/21/sending-a-azure-service-bus-message-in-asp-net-core/

Receiving messages in .Net Core: http://www.michalbialecki.com/2018/02/28/receiving-messages-azure-service-bus-net-core/


Unfortunately, as of time of this writing, your only options for using service bus are either to roll your own if you want to use Azure Storage, or an alternative third party library, such as Hangfire, which has a sort-of-queue in form of Sql Server storage.