🔗 Integration with MassTransit vs MediatR
|
|
📖 Overview
- MediatR: A lightweight in-process mediator library. It helps implement the CQRS and Mediator patterns by decoupling request senders from handlers inside the same application.
- MassTransit: A distributed application framework built on top of message brokers (RabbitMQ, Azure Service Bus, Kafka, etc.). It enables asynchronous messaging, Saga orchestration, and event-driven microservices.
🛠 Example in .NET Core
Using MediatR (In-Process Messaging)
// Install-Package MediatR.Extensions.Microsoft.DependencyInjection
// Command
public record CreateOrderCommand(string OrderId, string Customer) : IRequest<bool>;
// Handler
public class CreateOrderHandler : IRequestHandler<CreateOrderCommand, bool>
{
public Task<bool> Handle(CreateOrderCommand request, CancellationToken cancellationToken)
{
Console.WriteLine($"Order Created: {request.OrderId} for {request.Customer}");
return Task.FromResult(true);
}
}
// Usage
await mediator.Send(new CreateOrderCommand("123", "Alice"));
Using MassTransit (Distributed Messaging)
// Install-Package MassTransit
// Message Contract
public record OrderSubmitted(string OrderId, string Customer);
// Consumer
public class OrderSubmittedConsumer : IConsumer<OrderSubmitted>
{
public Task Consume(ConsumeContext<OrderSubmitted> context)
{
Console.WriteLine($"Order Received: {context.Message.OrderId} for {context.Message.Customer}");
return Task.CompletedTask;
}
}
// Configuration
services.AddMassTransit(x =>
{
x.AddConsumer<OrderSubmittedConsumer>();
x.UsingRabbitMq((context, cfg) =>
{
cfg.Host("localhost", "/", h => { });
cfg.ReceiveEndpoint("order-queue", e =>
{
e.ConfigureConsumer<OrderSubmittedConsumer>(context);
});
});
});
✅ Advantages
MediatR
- Lightweight and easy to set up.
- Great for CQRS and in-process decoupling.
- No external infrastructure required.
MassTransit
- Supports distributed, event-driven microservices.
- Built-in support for Sagas, retries, and fault handling.
- Integrates with RabbitMQ, Azure Service Bus, Kafka, etc.
⚠️ Disadvantages
MediatR
- Only works in-process (not distributed).
- No built-in support for retries or message durability.
MassTransit
- Requires external message broker setup and maintenance.
- More complex to configure and monitor.
🧭 Best Practices
- Use MediatR for in-process CQRS and request/response patterns.
- Use MassTransit for cross-service communication and long-running workflows.
- Combine both: MediatR for internal commands/queries, MassTransit for inter-service events.
- Ensure idempotency in handlers/consumers to avoid duplicate processing.
🔒 Precautions
- Secure MassTransit connections with TLS and proper credentials.
- Monitor broker health (RabbitMQ, Azure Service Bus, etc.).
- Handle retries and dead-letter queues in MassTransit.
- Keep MediatR handlers small and focused to avoid bloated logic.
🎯 Summary
MediatR is best for in-process decoupling and CQRS inside a single service.
MassTransit is best for distributed messaging across microservices.
In many real-world systems, they are used together: MediatR for internal commands/queries,
and MassTransit for inter-service communication and orchestration.
Comments and Discussion