By default message handling in MassTransit is done through Consumers. A consumer consumes one or more message types when configured on or connected to a receive endpoint. MassTransit includes many consumer types, including consumers, sagas, saga state machines, routing slip activities, handlers, and job consumers.
With the upcoming 8.1 release, an extra way to handle messages will be "Minimal Message Handlers". Instead of defining a separate Consumer class, a function is provided to handle a given message type, in the trend of the "minimal APIs" feature in ASP.NET Core.
To use this feature, you need to use the AddHandler
method on the IBusRegistrationConfigurator
:
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Reflection; | |
using System.Threading.Tasks; | |
using Microsoft.Extensions.Hosting; | |
using MassTransit; | |
using Microsoft.Extensions.DependencyInjection; | |
using Contracts; | |
using Microsoft.Extensions.Logging; | |
namespace GettingStarted | |
{ | |
public class Program | |
{ | |
public static async Task Main(string[] args) | |
{ | |
await CreateHostBuilder(args).Build().RunAsync(); | |
} | |
public static IHostBuilder CreateHostBuilder(string[] args) => | |
Host.CreateDefaultBuilder(args) | |
.ConfigureServices((hostContext, services) => | |
{ | |
services.AddHostedService<Worker>(); | |
services.AddMassTransit(x => | |
{ | |
x.SetKebabCaseEndpointNameFormatter(); | |
x.AddHandler(async (Contracts.GettingStarted request) => | |
{ | |
await Task.Delay(1000); | |
}); | |
x.UsingInMemory((context, cfg) => | |
{ | |
cfg.ConfigureEndpoints(context); | |
}); | |
}); | |
}); | |
} | |
} |
Of course in this example there is not much happening. Let us extend the example above and log the incoming request message. To inject extra dependencies, we can specify them as extra parameters to the method:
x.AddHandler(async (Contracts.GettingStarted request, ILogger<Program> logger) => | |
{ | |
await Task.Delay(1000); | |
logger.LogInformation($"Received: {request.Value}"); | |
}); |
Instead of passing the message directly, we can also use the ConsumeContext
to access the message metadata:
x.AddHandler(async (ConsumeContext<Contracts.GettingStarted> request, ILogger<Program> logger) => | |
{ | |
await Task.Delay(1000); | |
logger.LogInformation($"Received: {request.Message.Value}"); | |
}); |
If you want to learn more about Minimal Message Handlers, check out this video: