0Pricing
C# Academy · Lesson

Producing and Consuming Messages

Send and handle messages with MassTransit.

Registering MassTransit

Configure MassTransit in DI: register it, point it at a transport (here RabbitMQ), and let it discover your consumers.

builder.Services.AddMassTransit(x =>
{
    x.AddConsumers(typeof(Program).Assembly);
    x.UsingRabbitMq((context, cfg) =>
    {
        cfg.Host("localhost");
        cfg.ConfigureEndpoints(context);
    });
});

Defining A Consumer

A consumer implements IConsumer<T> for the message type it handles. Your logic lives in Consume, which receives a ConsumeContext<T>.

public class OrderPlacedConsumer : IConsumer<OrderPlaced>
{
    public async Task Consume(ConsumeContext<OrderPlaced> context)
    {
        OrderPlaced message = context.Message;
        // handle the event
    }
}

All lessons in this course

  1. Messaging Concepts
  2. Producing and Consuming Messages
  3. Sagas and Workflows
  4. Error Handling and Retries
← Back to C# Academy