0
0
RabbitmqHow-ToBeginner · 4 min read

How to Use RabbitMQ with C#: Simple Guide and Example

To use RabbitMQ with C#, install the RabbitMQ.Client NuGet package, create a connection to the RabbitMQ server, then use a IModel channel to declare queues and send or receive messages. Use BasicPublish to send and BasicConsume to receive messages asynchronously.
📐

Syntax

This is the basic pattern to connect and use RabbitMQ in C#:

  • Create a ConnectionFactory with server details.
  • Open a IConnection from the factory.
  • Create a IModel channel from the connection.
  • Declare a queue with QueueDeclare.
  • Publish messages with BasicPublish.
  • Consume messages with BasicConsume and an event handler.
csharp
var factory = new ConnectionFactory() { HostName = "localhost" };
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();

channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);

string message = "Hello World!";
var body = System.Text.Encoding.UTF8.GetBytes(message);

channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body);

var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) => {
    var body = ea.Body.ToArray();
    var message = System.Text.Encoding.UTF8.GetString(body);
    Console.WriteLine("Received: " + message);
};
channel.BasicConsume(queue: "hello", autoAck: true, consumer: consumer);
💻

Example

This example shows a complete C# console app that sends a message to a queue and listens for messages from the same queue.

csharp
using System;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;

class Program
{
    static void Main()
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using var connection = factory.CreateConnection();
        using var channel = connection.CreateModel();

        channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);

        string message = "Hello RabbitMQ from C#!";
        var body = Encoding.UTF8.GetBytes(message);

        channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body);
        Console.WriteLine(" [x] Sent {0}", message);

        var consumer = new EventingBasicConsumer(channel);
        consumer.Received += (model, ea) =>
        {
            var body = ea.Body.ToArray();
            var receivedMessage = Encoding.UTF8.GetString(body);
            Console.WriteLine(" [x] Received {0}", receivedMessage);
        };
        channel.BasicConsume(queue: "hello", autoAck: true, consumer: consumer);

        Console.WriteLine(" Press [enter] to exit.");
        Console.ReadLine();
    }
}
Output
[x] Sent Hello RabbitMQ from C#! [x] Received Hello RabbitMQ from C#!
⚠️

Common Pitfalls

Common mistakes when using RabbitMQ with C# include:

  • Not declaring the queue before publishing or consuming, causing errors.
  • Forgetting to keep the application running to receive messages asynchronously.
  • Using autoAck: false without manually acknowledging messages, which can cause message loss or re-delivery.
  • Not disposing connections and channels properly, leading to resource leaks.

Always declare queues on both sender and receiver sides and handle acknowledgments carefully.

csharp
/* Wrong: Not declaring queue before publishing */
channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body);

/* Right: Declare queue first */
channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);
channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body);
📊

Quick Reference

Here is a quick summary of key RabbitMQ C# client methods:

MethodPurpose
ConnectionFactoryCreates connection settings to RabbitMQ server
CreateConnection()Opens a connection to RabbitMQ
CreateModel()Creates a channel for communication
QueueDeclare()Declares a queue to send/receive messages
BasicPublish()Sends a message to a queue
BasicConsume()Starts receiving messages from a queue
EventingBasicConsumerHandles incoming messages asynchronously

Key Takeaways

Install RabbitMQ.Client NuGet package to use RabbitMQ in C#.
Always declare queues before publishing or consuming messages.
Use BasicPublish to send and BasicConsume with an event handler to receive messages.
Keep your app running to listen for messages asynchronously.
Dispose connections and channels properly to avoid resource leaks.