MassTransit for C# (.NET): Complete Guide with Examples
\n\n1. What It Is and Why It's Needed
\n\nMassTransit is a powerful, open-source, and widely used library for building distributed applications on the .NET platform. It provides a high-level abstraction over various message brokers, such as RabbitMQ, Azure Service Bus, Amazon SQS/SNS, ActiveMQ, and Kafka (via connectors). The main goal of MassTransit is to simplify the development of services that interact through asynchronous messages, freeing the developer from having to delve into the low-level details of a specific broker.
\n\nWhy is MassTransit needed? In modern microservice architecture, services need to communicate with each other reliably and asynchronously. Instead of direct HTTP calls (which can lead to cascading failures and tight coupling), message exchange is used. MassTransit handles complex tasks such as: managing connections and channels, retry attempts on failures, error handling, distributed transactions (via sagas), queue and topic management, message serialization/deserialization, and provides a convenient API for sending, publishing, and consuming messages.
\n\nThe library implements several key patterns: Command-Query Separation (via command sending), Publish-Subscribe (via event publishing), Request-Response (for synchronous exchange via asynchronous messages), and Saga Pattern (for managing long-running business processes). Thanks to this, MassTransit is the de facto standard for building reliable, scalable, and testable distributed systems on .NET.
\n\n2. Installation
\n\nMassTransit is installed via NuGet. Depending on the message broker you are using, you will need to install the main package and a package for the specific transport.
\n\nBasic installation (without transport):
\ndotnet add package MassTransit\n\nFor RabbitMQ:
\ndotnet add package MassTransit.RabbitMQ\n\nFor Azure Service Bus:
\ndotnet add package MassTransit.Azure.ServiceBus.Core\n\nFor Amazon SQS:
\ndotnet add package MassTransit.AmazonSQS\n\nFor Kafka:
\ndotnet add package MassTransit.Kafka\n\n3. Quick Start — Minimal Working Example
\n\nBelow is a simple example of sending and receiving a message using RabbitMQ. Make sure you have RabbitMQ running (e.g., via Docker: docker run -d --hostname my-rabbit --name some-rabbit -p 5672:5672 -p 15672:15672 rabbitmq:3-management).
using System;\nusing System.Threading.Tasks;\nusing MassTransit;\n\n// 1. Define the message contract\npublic record OrderSubmitted\n{\n public Guid OrderId { get; init; }\n public string CustomerName { get; init; }\n}\n\n// 2. Define the Consumer\npublic class OrderSubmittedConsumer : IConsumer<OrderSubmitted>\n{\n public async Task Consume(ConsumeContext<OrderSubmitted> context)\n {\n var message = context.Message;\n Console.WriteLine($"[Consumer] Received order: {message.OrderId} from {message.CustomerName}");\n await Task.CompletedTask;\n }\n}\n\n// 3. Configure and start the bus\npublic class Program\n{\n public static async Task Main()\n {\n var busControl = Bus.Factory.CreateUsingRabbitMq(cfg =>\n {\n cfg.Host("localhost", "/", h =>\n {\n h.Username("guest");\n h.Password("guest");\n });\n\n cfg.ReceiveEndpoint("order-queue",