Getting Started With RabbitMQ Using MassTransit

If you’ve ever used RabbitMQ with .NET, then you know it can be a bit tedious to setup and use even while utilizing the .NET library. MassTransit greatly simplifies using RabbitMQ from .NET. If you would like to learn more about MassTransit, check out the website here. This article will cover setting up a new Visual Studio 2019 project with the packages needed to implement MassTransit. This assumes you have already installed Erlang and RabbitMQ.

  1. Using Visual Studio 2019, create a new project.
  2. Choose the Console Application template.
  3. Name the project whatever you wish.
  4. Choose .NET 5.0 as the Target Framework.
  5. Using the Nuget Package Manager, add the following packages: MassTransit, MassTransit.AspNetCore, and MassTransit.RabbitMQ.

Create a class named RabbitMqConfig to contain RabbitMQ configuration:

public class RabbitMqConfig
{
	public const string RabbitMqRootUri = "rabbitmq://localhost";
	public const string RabbitMqUri = "rabbitmq://localhost/FirstQueue?bind=true";
	public const string UserName = "guest";
	public const string Password = "guest";
}

Here’s something very important. If you are running a local instance of RabbitMQ, you can use the guest user. However, if the RabbitMQ instance you’re connecting to is not local, you must create a user name and password and set permissions otherwise you won’t be able to connect to RabbitMQ.

Since I like using dependency injection, add the following using statement:

using Microsoft.Extensions.DependencyInjection;

Let’s add a static class variable to hold a reference to IBus:

private static IBus _bus;

Now, let’s define a ServiceCollection and add MassTransit and it’s dependencies to it:

var services = new ServiceCollection()
	.AddMassTransit(x =>
		{
			x.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(config =>
			{
				config.Host(new Uri(RabbitMqConfig.RabbitMqRootUri), h =>
				{
					h.Username(RabbitMqConfig.UserName);
					h.Password(RabbitMqConfig.Password);
				});
			}));
		})
	.AddMassTransitHostedService().BuildServiceProvider();

FInally, retrieve the service from the collection and assign it to the static class variable:

_bus = services.GetService<IBus>();

That’s all for now. Check back for another article on how to send to and receive data from RabbitMQ using MassTransit.

About the Author

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You may also like these