Introduction
In the previous lesson, we prepared the message contract, producer service, and database integration. In this lesson, we will implement the consuming side. Reading a message from RabbitMQ is only one part of the job. A production-ready consumer must deserialize the payload, invoke the correct application service, resolve database-related dependencies within the correct scope, acknowledge the message only after successful processing, and clean up its resources when the application stops.
These responsibilities should not be implemented inside a controller or an unmanaged Task.Run call. A RabbitMQ consumer should be modeled as an ASP.NET Core BackgroundService that participates in the host lifecycle. It starts with the application, observes the shutdown token, stops the subscription during shutdown, and releases the channel and connection in a controlled manner.
Our example scenario will consume an OrderCreated message. The consumer will receive the message, copy and deserialize its JSON body into an OrderCreatedMessage object, resolve a scoped application service, process the order, and acknowledge the delivery after the business operation completes successfully.
Responsibilities of a consumer pipeline
A maintainable consumer pipeline can be divided into the following stages:
- Message delivery: RabbitMQ invokes the consumer callback when a delivery arrives.
- Payload copying: The body supplied by the RabbitMQ .NET client should be copied immediately when it must be used beyond the delivery callback.
- Deserialization: The JSON payload is converted into the known message contract.
- Scope creation: A new dependency injection scope is created for scoped application services and database contexts.
- Business processing: The message is passed to an application service.
- Logging: Message ID, correlation ID, and delivery tag are included in structured logs.
- Acknowledgement:
BasicAckAsyncis called only after successful processing. - Error and resource handling: Failures are logged, and the channel and connection are disposed during shutdown.
This separation prevents the consumer class from becoming a large application service. The consumer should coordinate messaging infrastructure, while the application service should enforce domain and business rules.
Why scoped services require an explicit scope
A BackgroundService is registered as a singleton by the dependency injection container. In contrast, an Entity Framework Core DbContext is normally registered with a scoped lifetime. Therefore, injecting a DbContext or another scoped processing service directly into the consumer constructor is incorrect.
The recommended approach is to inject IServiceScopeFactory and create a scope for each message. Each delivery then receives its own scoped dependencies, and those dependencies are disposed when processing ends. Reusing one DbContext instance throughout the lifetime of a long-running consumer can cause tracked entities to accumulate, create thread-safety problems, and produce unexpected state between messages.
Message contract and processing service
We can use a record similar to the contract introduced in the previous lesson:
public sealed record OrderCreatedMessage(
Guid MessageId,
Guid OrderId,
string CustomerEmail,
decimal TotalAmount,
DateTimeOffset OccurredAt,
string CorrelationId);To keep business logic outside the consumer, define a scoped processing service:
public interface IOrderMessageProcessor
{
Task ProcessAsync(
OrderCreatedMessage message,
CancellationToken cancellationToken);
}
public sealed class OrderMessageProcessor(
AppDbContext dbContext,
ILogger<OrderMessageProcessor> logger)
: IOrderMessageProcessor
{
public async Task ProcessAsync(
OrderCreatedMessage message,
CancellationToken cancellationToken)
{
logger.LogInformation(
"Processing order. OrderId: {OrderId}, MessageId: {MessageId}",
message.OrderId,
message.MessageId);
var alreadyProcessed = await dbContext.ProcessedMessages
.AnyAsync(x => x.MessageId == message.MessageId, cancellationToken);
if (alreadyProcessed)
{
logger.LogInformation(
"Message has already been processed. MessageId: {MessageId}",
message.MessageId);
return;
}
dbContext.ProcessedMessages.Add(new ProcessedMessage
{
MessageId = message.MessageId,
ProcessedAt = DateTimeOffset.UtcNow
});
await dbContext.SaveChangesAsync(cancellationToken);
}
}The lookup provides a simple idempotency mechanism. If RabbitMQ redelivers the same message, the MessageId can be used to detect that it was already processed. In a real application, create a unique database index for this value as an additional protection against concurrent duplicate deliveries.
Registering the RabbitMQ infrastructure
A RabbitMQ connection is a long-lived resource. A channel is also normally reused for a consumer rather than recreated for every delivery. Opening a new connection or channel for each message is expensive and makes failure handling more complicated. A basic registration may look like this:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IConnection>(serviceProvider =>
{
var configuration = serviceProvider
.GetRequiredService<IConfiguration>();
var factory = new ConnectionFactory
{
Uri = new Uri(configuration["RabbitMq:Uri"]!)
};
return factory.CreateConnectionAsync().GetAwaiter().GetResult();
});
builder.Services.AddScoped<IOrderMessageProcessor, OrderMessageProcessor>();
builder.Services.AddHostedService<OrderCreatedConsumer>();In a more advanced design, asynchronous connection initialization can be managed by a dedicated hosted service or an asynchronous factory instead of synchronously blocking during service registration. The important point here is that the hosted consumer owns the channel it uses and that the connection lifecycle is managed explicitly. Production systems should also define a reconnection strategy for broker or network failures.
The BackgroundService-based consumer
The following class connects RabbitMQ consumption to the ASP.NET Core host lifecycle:
public sealed class OrderCreatedConsumer(
IConnection connection,
IServiceScopeFactory scopeFactory,
ILogger<OrderCreatedConsumer> logger)
: BackgroundService
{
private const string QueueName = "orders.created";
private IChannel? _channel;
private string? _consumerTag;
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
_channel = await connection.CreateChannelAsync();
await _channel.QueueDeclareAsync(
queue: QueueName,
durable: true,
exclusive: false,
autoDelete: false,
arguments: null,
cancellationToken: stoppingToken);
await _channel.BasicQosAsync(
prefetchSize: 0,
prefetchCount: 10,
global: false,
cancellationToken: stoppingToken);
var consumer = new AsyncEventingBasicConsumer(_channel);
consumer.ReceivedAsync += HandleMessageAsync;
_consumerTag = await _channel.BasicConsumeAsync(
queue: QueueName,
autoAck: false,
consumer: consumer,
cancellationToken: stoppingToken);
logger.LogInformation(
"RabbitMQ consumer started. Queue: {QueueName}, ConsumerTag: {ConsumerTag}",
QueueName,
_consumerTag);
try
{
await Task.Delay(Timeout.InfiniteTimeSpan, stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
logger.LogInformation("Consumer is stopping.");
}
}
private async Task HandleMessageAsync(
object sender,
BasicDeliverEventArgs eventArgs)
{
if (_channel is null)
{
return;
}
var body = eventArgs.Body.ToArray();
var messageId = eventArgs.BasicProperties.MessageId;
try
{
var message = JsonSerializer.Deserialize<OrderCreatedMessage>(body)
?? throw new JsonException("Message body is null.");
await using var scope = scopeFactory.CreateAsyncScope();
var processor = scope.ServiceProvider
.GetRequiredService<IOrderMessageProcessor>();
using var logScope = logger.BeginScope(new Dictionary<string, object>
{
["MessageId"] = message.MessageId,
["CorrelationId"] = message.CorrelationId,
["DeliveryTag"] = eventArgs.DeliveryTag
});
await processor.ProcessAsync(message, CancellationToken.None);
await _channel.BasicAckAsync(
eventArgs.DeliveryTag,
multiple: false);
logger.LogInformation(
"Message processed successfully and acknowledged.");
}
catch (JsonException exception)
{
logger.LogError(
exception,
"Message could not be deserialized. MessageId: {MessageId}",
messageId);
await _channel.BasicNackAsync(
eventArgs.DeliveryTag,
multiple: false,
requeue: false);
}
catch (Exception exception)
{
logger.LogError(
exception,
"Message processing failed. MessageId: {MessageId}",
messageId);
await _channel.BasicNackAsync(
eventArgs.DeliveryTag,
multiple: false,
requeue: true);
}
}
public override async Task StopAsync(
CancellationToken cancellationToken)
{
if (_channel is not null && _consumerTag is not null)
{
await _channel.BasicCancelAsync(
_consumerTag,
cancellationToken: cancellationToken);
}
if (_channel is not null)
{
await _channel.DisposeAsync();
}
await base.StopAsync(cancellationToken);
}
}The example uses autoAck: false, so RabbitMQ does not consider the delivery complete before the application confirms it. BasicAckAsync is called only after business processing succeeds. A deserialization error is treated as a non-transient failure and is rejected with requeue: false. To avoid losing such a message, the queue should later be configured with a dead-letter exchange.
Cancellation and shutdown behavior
When the host shuts down, stoppingToken is cancelled. The consumer must not remain blocked forever; it should stop its subscription, release the channel, and allow the host to finish shutting down. Using Task.Delay(Timeout.InfiniteTimeSpan, stoppingToken) ties the lifetime of the background service to the host cancellation token.
The processing service should also accept a cancellation token. The RabbitMQ event callback used in this example does not expose the host token directly, so CancellationToken.None is passed to the business method. A more advanced implementation can retain the stopping token in the consumer or use a processing abstraction that observes application shutdown. Cancellation support is particularly important when a message performs a long database or external API operation.
Common mistakes
- Injecting DbContext into the consumer constructor: Because the BackgroundService is a singleton, the scoped context would be retained with the wrong lifetime.
- Using the message body later without copying it: Copy
ReadOnlyMemory<byte>immediately withToArray()when the payload must outlive the callback operation. - Acknowledging before processing: An early ACK prevents redelivery even if the application fails during business processing.
- Requeuing every failure: A permanently malformed message can create a tight redelivery loop and consume all consumer capacity.
- Starting unlimited parallel work: Prefetch, channel dispatch behavior, and database capacity must be considered before increasing concurrency.
- Ignoring shutdown: Without cancellation, consumer cancellation, and disposal, the process may leave open resources or interrupt work unpredictably.
- Missing correlation information: Without message and correlation IDs, tracing one operation across producer, consumer, and database logs becomes difficult.
Practice exercise
Complete the following exercise:
- Add the
OrderCreatedConsumerto the application. - Register
OrderMessageProcessorwith a scoped lifetime. - Publish a valid
OrderCreatedMessageto the queue from the RabbitMQ management interface or the producer API. - Observe the order of deserialization, business processing, and acknowledgement in the logs.
- Publish invalid JSON and verify the
BasicNackAsyncbehavior. - Publish two messages with the same
MessageIdand verify that idempotency prevents duplicate processing. - Stop the application and inspect the consumer cancellation and disposal behavior.
Conclusion
In this lesson, we moved RabbitMQ consumption into an ASP.NET Core BackgroundService and organized the work as an explicit processing pipeline. The consumer copied the payload, deserialized the message contract, resolved a scoped service from a fresh scope, added structured logging, and acknowledged the message only after successful processing.
This design provides a strong foundation for background message processing that is independent from HTTP request execution and aligned with the application host lifecycle. In the next stage, we will address retry policies, dead-letter queues, and the distinction between transient and permanent failures. These mechanisms will help us build a consumer that remains reliable not only when everything works, but also when external systems fail and malformed messages enter the queue.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/core/extensions/scoped-service
- https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection
- https://www.rabbitmq.com/docs/client-libraries/dotnet-api-guide
- https://www.rabbitmq.com/docs/confirms