NServiceBus integrates with ASP.NET Core 3.x using GenericHost
. For older versions of ASP.NET Core use the community package Community.NServiceBus.WebHost. ASP.NET Core 2.x has a race condition and the community package implements a workaround. It's recommended to upgrade to ASP.NET Core 3.0 and use NServiceBus.Extensions.Hosting package.
This sample shows how to send messages to an NServiceBus endpoint from an ASP.NET Core WebAPI application.
Running the solution
When the solution is run, a new browser window/tab opens, as well as a console application. The browser will navigate to http:/
.
An async WebAPI controller handles the request. It creates an NServiceBus message and sends it to the endpoint running in the console application. The message has been processed successfully when the console application prints "Message received at endpoint".
Prerequisites
- Visual Studio 2019 is required to run this sample.
Initialize the WebAPI endpoint
Open Program.
and look at the UseNServiceBus
method.
A Send-Only endpoint named Samples.
is configured in the WebAPI application by creating a new EndpointConfiguration
.
var builder = WebApplication.CreateBuilder();
builder.Host.UseNServiceBus(context =>
{
var endpointConfiguration = new EndpointConfiguration("Samples.ASPNETCore.Sender");
var transport = endpointConfiguration.UseTransport<LearningTransport>();
transport.Routing().RouteToEndpoint(
assembly: typeof(MyMessage).Assembly,
destination: "Samples.ASPNETCore.Endpoint");
endpointConfiguration.SendOnly();
return endpointConfiguration;
});
Routing is configured to send every message from the assembly containing MyMessage
to the Samples.
endpoint.
Injection into the Controller
The message session is injected into SendMessageController
via constructor injection.
public SendMessageController(IMessageSession messageSession)
{
this.messageSession = messageSession;
}
Sending the message
Send messages through the IMessageSession
instance provided by ASP.NET Core.
[HttpGet]
public async Task<string> Get()
{
var message = new MyMessage();
await messageSession.Send(message);
return "Message sent to endpoint";
}
Processing the message
The message is picked up and processed by a message handler in the Samples.
endpoint.
public Task Handle(MyMessage message, IMessageHandlerContext context)
{
log.Info("Message received at endpoint");
return Task.CompletedTask;
}