A Beginners Guideline to RabbitMq and MassTransit(Part 2): Implement RabbitMQ in Code with MassTransit

tong eric
Bina Nusantara IT Division
7 min readDec 29, 2021

Implementation and Explanation About Using RabbitMq With MassTransit

Picture by Marvin Meyer on Unsplash

This article is a three-part series about complete implementation of RabbitMq as message broker . You can navigate to other part by link below :

Part 1 : RabbitMq and How To Install it

Part 3 : User Access Management and Good Practice for Using RabbitMq

RabbitMQ implements AMQP and it’s programmable. It supports a lot of languages like Nodejs, Python, C#, Java, and many more. You can choose those libraries based on your application needs. Today we will try to use one of those libraries, MassTransit.

What is MassTransit

MassTransit is a free, open-source distributed application framework for .NET. MassTransit makes it easy to create applications and services that leverage message-based, loosely-coupled asynchronous communication for higher availability, reliability, and scalability. It aims to be a .NET-friendly abstraction over the messaging technologies MSMQ (Microsoft Message Queuing) and RabbitMQ. As such it brings a lot of the application-specific logic closer to the programmer in an easy-to-configure manner.

Below I listed the benefits that we can get from using MassTransit :

1. Exception Management

MassTransit provides an ability to automatically reconnect and handle failures when something happens to your connection to the queue server.

2. Retries Queue

Upon failure, MassTransit will move your message to a separate error queue. It allows you to inspect failure messages and you can even shovel them back to the main queue.

If exceptions are thrown from your consumers. It will not immediately move it to the error queue. MassTransit will try to re-queue the message by several tries before moving it to the error queue.

3. Serialization

MassTransit provides a number of serializers, including BSON, JSON, XML, and Binary. You can handle those types of data with ease with those serializers.

4. Diagnostic, Tracing, and Monitoring

MassTransit provides a full developer kit and function to simplify diagnostic progress. A tracing functionality simplified developer for tracing detailed timings of message consumed, message rate for receive and consume, and what exceptions are thrown if any exceptions occurred. You can check for your queue health state using the performance counter from this library and System.Diagnostics namespace.

5. Unit-Testable

MassTransit provides an in-memory transport bus that allows you to modify and use for your integration tests. Furthermore, the TestFactory allows you to easily set up both in-memory transport and real transport-based unit tests for your consumers.

Getting Started with MassTransit

Getting started with MassTransit is fast and easy, for prerequisite you will need a .NET 5 SDK to be installed.

There are 2 kinds of applications that use MassTransit to connect to brokers, a consumer and publisher. Let’s start by making a consumer project first. Consumer projects will listen and consume a queue from your service bus (RabbitMQ or In-Memory or Azure Service Bus). you can configure your consumer in any kind of project that is based on .NET. For this tutorial, however, let’s try to make a consumer use background worker service.

Consumer Example

Create a new directory for this example project, direct to that folder, and then open up the command prompt from that directory.

dotnet new worker -n Example.WorkerService

Use this command to create a basic template for worker service. Try to run that project and you will get some results:

Now let’s start by configuring a consumer queue with an in-memory service bus.

Add MassTransit.AspNetCore packages by command below.

dotnet add package MassTransit.AspNetCore

You can add this package via NuGet manager if you are using Microsoft Visual Studio. Navigate to dependencies of your project, right-click on packages then click to manage NuGet packages. Find this package by typing MassTransit.AspNetCore in the search bar and then install it.

Edit your Program.cs like below for the configuration.

Don’t forget to add using MassTransit on top of code as references for using this library.

MassTransit can be used by using the function AddMassTransit in your services. UsingInMemory function is to define a service bus that we will use for this case, then we configure the endpoint by default context of this application. After that, we add the hosted service of MassTransit by using the AddMassTransitHostedService function.

Next, let’s create a consumer class that will handle a queue from this bus.

Here is a simple consumer to handle messages from MassTransit. Basically, the consumer for MassTransit is created by extending the IConsumer<T> interface.

T is to inform the class model of the message that will be consumed and make sure you create a message model by using the same namespace from consumer and publisher because MassTransit divides exchange by their model namespace.

Task Consumer will be triggered when there is a message in your queue.

After that add your consumer to configuration by adding the code below in your Program.cs before UsingInMemory.

Then you can run the project again and The output should have changed to show the message consumer generating the output.

To configure your consumer to listen to the queue from RabbitMq, just simply replace the UsingInMemory function with the code below.

Replace <connection_string> with your RabbitMQ connection string and <queue name> with the queue name you want to listen to. MassTransit will create a new queue based on the name in there if that queue does not exist so be careful with it.

And don’t forget to add a library for RabbitMQ with the command below

dotnet add package MassTransit.RabbitMQ

At this point, the service can connect to RabbitMQ and is publishing messages which are received by the consumer.

Publisher Example

The publisher can be implemented to any application that is based on the .NET. In this tutorial, we will try to create a publisher for RabbitMQ in console apps. Create a new directory for this example project, direct to that folder, and then open up the command prompt from that directory.

dotnet new console -n Example.Publisher -f 5.0

Use this command to generate a base project for your console application.

After that add the package needed from the list below with console commands or with NuGet package manager, for example:

  • MassTransit
dotnet add package MassTransit
  • MassTransit.RabbitMQ
dotnet add package MassTransit.RabbitMQ

In the generated project, create a class name RabbitMqSingleton.cs

This is a singleton class that is used to send your message to the queue. Every time you call GetInstance it will return the same instance for you. The instance is created using the BusFactory of MassTransit that uses the CreateUsingRabbitMq function.

After that create a Message class using the same namespace with the receiver.

Now the preparation for sending messages is all done. To send a message edit your Program.cs like the example below.

Replace connection_string and queue_name with the correct value.Then run your project, you will

see results like the following image below.

Check your dashboard to confirm that the message is already in the queue.

Best Practice For Code

There are a couple of things that you can try when implementing RabbitMQ using MassTransit.

Single Out Message Model

Exchanges play an important role while using RabbitMQ. Consumers identify which message they should consume by using exchanges. With MassTransit, your exchanges are automatically set by this library to be divided by namespace. To make sure that your model can have the same namespace between publisher and consumer code, we can single out the message model to a different project then it can be shared between the publisher solution file and consumer solution file. Note that if those solutions are divided into different repositories, make sure to commit and push a change in both of them if there are any updates on that model.

Singleton concept

RabbitMQ creates a connection every time you initialize a bus instance by using BusFactory, so to decrease a connection that is created, use the singleton concept while creating a bus from it. Singleton means that only one object of its kind exists and provides a single point of access to it for any other code. The example on top is already shown how to create a RabbitMqSingleton class that will initialize only one time when a project is running.

Private Out Configuration File

To access RabbitMQ, you need a connection string and the proper queue name that your application wants to consume/publish. Putting those values in the configuration file will give you plenty of benefits like you can easily change between production and development servers, change queue names based on the application environment, and secure out your production server access to your system admin (no to the developer).

Conclusion

To summarize, MassTransit is a library that we can implement for using RabbitMq more efficiently. For proper message broker architecture we will have 2 main components :

  • Message Publisher
  • Message Consumer

And here is some best concept for us to follow while designing broker application :

Single Out Message Model

  • Single Out Message Model
  • Singleton concept
  • Private Out Configuration File

--

--