DEV Community

Cover image for ๐Ÿš€ Getting Started with RabbitMQ Pub/Sub using MassTransit in .NET
Gaurav
Gaurav

Posted on

๐Ÿš€ Getting Started with RabbitMQ Pub/Sub using MassTransit in .NET

In this guide, weโ€™ll set up a Publisher/Consumer architecture using RabbitMQ and MassTransit in .NET. Weโ€™ll cover:

  • Docker setup for RabbitMQ
  • Publisher configuration in ASP.NET Core
  • Consumer setup in a .NET Console App
  • Sending and receiving messages

๐Ÿณ Step 1: Run RabbitMQ in Docker
Create a file named docker-compose.yml with the following content:

version: '3'
services:
  rabbitmq:
    image: rabbitmq:3-management
    container_name: rabbitmq
    ports:
      - "5672:5672"
      - "15672:15672"
    environment:
      RABBITMQ_DEFAULT_USER: guest
      RABBITMQ_DEFAULT_PASS: guest
Enter fullscreen mode Exit fullscreen mode

Then run:

docker-compose up -d
Enter fullscreen mode Exit fullscreen mode

โœ… RabbitMQ Management UI: http://localhost:15672
Username: guest
Password: guest

๐Ÿ“† Step 2: Create the Shared Event Model

This model will be shared between publisher and consumer:

namespace Response.EventModel;

public class EventModel
{
    public string message { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“จ Step 3: Setup the Publisher in ASP.NET Core

๐Ÿ”น Add NuGet Packages

<PackageReference Include="MassTransit" Version="8.4.1" />
<PackageReference Include="MassTransit.RabbitMQ" Version="8.4.1" />
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Create the Publisher Class

using MassTransit;
using Response.EventModel;

namespace TechnicianAdmin.Event;

public class Publisher
{
    private readonly IPublishEndpoint _publishEndpoint;

    public Publisher(IPublishEndpoint publishEndpoint)
    {
        _publishEndpoint = publishEndpoint;
    }

    public async Task PublishMessage()
    {
        var message = new EventModel
        {
            message = "Hey this is testing message from publisher"
        };

        await _publishEndpoint.Publish(message);
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Register MassTransit in Dependency Injection

using MassTransit;
using TechnicianAdmin.Event;

public static class AddMassTransitConfiguration
{
    public static IServiceCollection MassTransitConfiguration(this IServiceCollection services)
    {
        services.AddTransient<Publisher>();

        services.AddMassTransit(x =>
        {
            x.SetKebabCaseEndpointNameFormatter();

            // Auto-discover consumers in the assembly (optional)
            x.AddConsumers(typeof(Program).Assembly);

            x.UsingRabbitMq((context, cfg) =>
            {
                cfg.Host("localhost", "/", h =>
                {
                    h.Username("guest");
                    h.Password("guest");
                });

                cfg.ConfigureEndpoints(context);
            });
        });

        return services;
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Inject and Use Publisher in Controller

private readonly Publisher _publishEndpoint;

public Controller(Publisher publishEndpoint)
{
    _publishEndpoint = publishEndpoint;
}

[AllowAnonymous]
[HttpGet("publish-rabbitMQ-message")]
public async Task<IActionResult> SendMessage()
{
    await _publishEndpoint.PublishMessage();
    return Ok("Message sent to RabbitMQ");
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ—’๏ธ Step 4: Setup the Consumer in a .NET Console App

๐Ÿ”น Add NuGet Packages

<PackageReference Include="MassTransit.RabbitMQ" Version="8.4.1" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="9.0.5" />
<PackageReference Include="RabbitMQ.Client" Version="7.1.2" />
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Create the EventModel Again (or Share It via Class Library)

namespace Response.EventModel;

public class EventModel
{
    public string message { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Create the Consumer

using MassTransit;
using Response.EventModel;

namespace ConsoleApp1;

public class HelloMessageConsumer : IConsumer<EventModel>
{
    public Task Consume(ConsumeContext<EventModel> context)
    {
        Console.WriteLine($"Received message: {context.Message.message}");
        return Task.CompletedTask;
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Setup MassTransit in Program.cs

using ConsoleApp1;
using MassTransit;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateDefaultBuilder(args);

builder.ConfigureServices((hostContext, services) =>
{
    services.AddMassTransit(x =>
    {
        x.AddConsumer<HelloMessageConsumer>();

        x.UsingRabbitMq((context, cfg) =>
        {
            cfg.Host("localhost", "/", h =>
            {
                h.Username("guest");
                h.Password("guest");
            });

            cfg.ReceiveEndpoint("hello-message-queue", e =>
            {
                e.ConfigureConsumer<HelloMessageConsumer>(context);
            });
        });
    });
});

await builder.Build().RunAsync();
Enter fullscreen mode Exit fullscreen mode

โœ… Test the Flow

  1. Make sure RabbitMQ is running via Docker.
  2. Run the consumer app.
  3. Hit the API endpoint:GET http://localhost:/publish-rabbitMQ-message
  4. You should see output like:

Received message: Hey this is testing message from publisher

๐Ÿง  Conclusion

Congrats! ๐ŸŽ‰ Youโ€™ve successfully:

  • Set up RabbitMQ using Docker
  • Published a message via ASP.NET Core
  • Consumed it via a .NET Console App This pattern forms the foundation of microservices-based communication using MassTransit + RabbitMQ in the .NET ecosystem.

Top comments (0)