0Pricing
C# Academy · Lesson

Producing and Consuming Messages

Send and handle messages with MassTransit.

Producing and Consuming Messages is a free C# Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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
    }
}

Publishing An Event

Inject IPublishEndpoint and call Publish to broadcast an event to all subscribers.

public class OrderService
{
    private readonly IPublishEndpoint _publish;
    public OrderService(IPublishEndpoint publish) => _publish = publish;

    public Task PlaceOrderAsync(Guid id, string email) =>
        _publish.Publish(new OrderPlaced(id, email));
}

Sending A Command

Commands go to a specific endpoint. Resolve an ISendEndpoint for the destination and call Send.

var endpoint = await _sendProvider
    .GetSendEndpoint(new Uri("queue:charge-payment"));
await endpoint.Send(new ChargePayment(orderId, amount));

Publish vs Send Recap

Publish is for events and reaches every subscribed consumer; Send is for commands and targets one queue. Choosing correctly defines your routing behavior.

Consume Context Power

ConsumeContext exposes more than the message: correlation ids, headers, and the ability to publish or respond from within a consumer, enabling message chaining.

public async Task Consume(ConsumeContext<OrderPlaced> context)
{
    await context.Publish(new InvoiceRequested(context.Message.OrderId));
}

Request-Response

MassTransit also supports request-response over messaging. A request client sends a request and awaits a typed reply, useful when you need an answer but still want broker decoupling.

var response = await _client
    .GetResponse<OrderStatus>(new GetOrder(orderId));
OrderStatus status = response.Message;

Endpoint Naming

ConfigureEndpoints auto-names a receive endpoint (queue) per consumer using conventions. You can customize names with formatters or explicit configuration when needed.

Message Serialization

By default MassTransit serializes messages as JSON and includes metadata (message type, ids). Producers and consumers share the message contract types, often in a shared package.

Concurrency

A consumer can process many messages in parallel. Tune PrefetchCount and concurrency limits to balance throughput against downstream capacity.

cfg.ReceiveEndpoint("orders", e =>
{
    e.PrefetchCount = 16;
    e.ConcurrentMessageLimit = 8;
    e.ConfigureConsumer<OrderPlacedConsumer>(context);
});

Testing Consumers

MassTransit ships an in-memory test harness so you can publish a message and assert a consumer handled it, without a real broker.

Quick Check

Test producing and consuming.

Recap

Register MassTransit with AddMassTransit, a transport, and ConfigureEndpoints. Consumers implement IConsumer<T> with a Consume method. Use IPublishEndpoint.Publish for events (all subscribers) and ISendEndpoint.Send for commands (one queue). ConsumeContext enables chaining and request-response, and a test harness verifies consumers in-memory.

Frequently asked questions

Is the “Producing and Consuming Messages” lesson free?

Yes — the full text of “Producing and Consuming Messages” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “Producing and Consuming Messages”?

Send and handle messages with MassTransit. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Producing and Consuming Messages” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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