Prerequisites
Azure service bus and queue or topic need to be created on azure
portal.
Step 1:
We need to install “Microsoft.Azure.ServiceBus” nuget package
in our project.
Step 2:
We will create static method using which we can send message
to any queue or topic from anywhere in the solution using this
method.
So here is the code for that method:
using Microsoft.Azure.ServiceBus;
using Newtonsoft.Json;
using System;
using System.Reflection;
using System.Text;
namespace ServiceBusExample
{
public class AzureServiceBusPublisher
{
private static readonly string ConnectionString = “enter your service bus connection string here”;
private static
IQueueClient _queueClient { get; set; }
private static
ITopicClient _topicClient;
public static void Publish<T>(T message, string name, ClientType clientType)
{
var serializedMessage = JsonConvert.SerializeObject(message);
var m = new
Message(Encoding.UTF8.GetBytes(serializedMessage))
{
ContentType = "application/json"
};
try
{
LogServices.LogInformation(new
LogEntry(MethodBase.GetCurrentMethod())
{
Message = $"Publishing message to Azure Service bus. MessageContent: {serializedMessage}"
});
if (clientType == ClientType.Queue)
{
_queueClient = new QueueClient(ConnectionString,
name);
_queueClient.SendAsync(m).GetAwaiter().GetResult();
}
if (clientType == ClientType.Topic)
{
_topicClient = new TopicClient(ConnectionString,
name);
_topicClient.SendAsync(m).GetAwaiter().GetResult();
}
}
catch (Exception ex)
{
// log error
}
}
}
public enum ClientType
{
Queue,
Topic
}
}
Step 3:
Now we can us method anywhere in the solution. This is an
example how we will call this method.
AzureServiceBusPublisher.Publish(model,
queueName, ClientType.Queue);
This method has three parameters. In first parameter we can
pass any strongly type model. In second parameter we have to pass queue or topic
name. And third parameter is for client type.