Skip to content

Create a Message Consumer

A message consumer, the most common consumer type, is a class that consumes one or more messages types. For each message type, the class implements the IConsumer<TMessage> interface that has a single Consume method.

To create a message consumer:

Create a new project (or use an existing project) using the class library template. If you’re using an existing project, skip this step.

Terminal window
dotnet new classlib -o ./src/MyProject.Components
dotnet sln add ./src/MyProject.Components

Add a reference to the message contract project using your IDE, or by running the following command from the command line.

Terminal window
dotnet reference add ./src/MyProject.Contracts --project ./src/MyProject.Components

Create a new class in the MyProject.Components project. To keep components organized, create a new folder for consumers.

./src/MyProject.Components/Consumers/CreateCustomerConsumer.cs
namespace MyProject.Components.Consumers;
using MassTransit;
using MyProject.Contracts;
public class CreateCustomerConsumer :
IConsumer<CreateCustomer>
{
public async Task Consume(ConsumeContext<CreateCustomer> context)
{
// Handle the message
}
}

Message consumers can have dependencies injected into their constructors. For example, if the consumer needs to access a database, inject the database context into the consumer’s constructor. You may also want to inject other services, such as an ILogger<T> instance.

./src/MyProject.Components/Consumers/CreateCustomerConsumer.cs
namespace MyProject.Components.Consumers;
using MassTransit;
using Microsoft.EntityFrameworkCore;
using MyProject.Contracts;
public class CreateCustomerConsumer :
IConsumer<CreateCustomer>
{
readonly DbContext _dbContext;
readonly ILogger<CreateCustomerConsumer> _logger;
public CreateCustomerConsumer(DbContext dbContext, ILogger<CreateCustomerConsumer> logger)
{
_dbContext = dbContext;
_logger = logger;
}
public async Task Consume(ConsumeContext<CreateCustomer> context)
{
_logger.LogInformation("Creating customer {CustomerName}", context.Message.CustomerName);
await _dbContext.Customers.AddAsync(new Customer(context.Message.CustomerName));
await _dbContext.SaveChangesAsync();
await context.Publish(new CustomerCreated(context.Message.CustomerName));
}
}

Once you’ve created a message consumer, you can learn about testing a consumer to verify that it’s working correctly.