Getting Started
Architecture
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

NServiceBus in ASP.NET

NuGet Package: NServiceBus.Extensions.Hosting (1.x)
Target Version: NServiceBus 7.x

NServiceBus easily integrates with ASP.NET Core applications.

Minimal APIs

ASP.NET 6 introduced a new hosting API with the ASP.NET minimal APIs. The NServiceBus.Extensions.Hosting package is fully compatible with the minimal API's WebApplication host:

var builder = WebApplication.CreateBuilder();

builder.Host.UseNServiceBus(context =>
{
    var endpointConfiguration = new EndpointConfiguration("MyWebAppEndpoint");

    // configure the endpoint

    return endpointConfiguration;
});

var host = builder.Build();

// further ASP.NET configuration

host.Run();

Generic Host

Starting with ASP.NET 3, the NServiceBus Generic Host support provides integration with ASP.NET Core applications:

var builder = Host.CreateDefaultBuilder()
    .UseNServiceBus(context =>
    {
        var endpointConfiguration = new EndpointConfiguration("MyWebAppEndpoint");

        // configure the endpoint

        return endpointConfiguration;
    })
    .ConfigureWebHostDefaults(webHost => webHost.UseStartup<Startup>())
    .Build();

builder.Run();

Dependency injection

Messages can be sent with NServiceBus using the IMessageSession API which is available via the dependency injection container.

Web API controllers

[ApiController]
class WebApiController : ControllerBase
{
    IMessageSession messageSession;

    public WebApiController(IMessageSession messageSession)
    {
        this.messageSession = messageSession;
    }

    [HttpGet]
    public async Task<ActionResult> Get()
    {
        await messageSession.Send(new MessageFromWebApi());
        return Ok("message was sent successfully");
    }
}

MVC controllers

public class MvcController : Controller
{
    IMessageSession messageSession;

    public MvcController(IMessageSession messageSession)
    {
        this.messageSession = messageSession;
    }

    public ViewResult Index()
    {
        return View();
    }

    public async Task<ViewResult> SendMessage()
    {
        await messageSession.Send(new MessageFromMvc());
        return View();
    }
}

Razor Pages

public class RazorPage : PageModel
{
    IMessageSession messageSession;

    public RazorPage(IMessageSession messageSession)
    {
        this.messageSession = messageSession;
    }

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        await messageSession.Send(new MessageFromRazorPage());
        return RedirectToPage("./Success");
    }
}

Older ASP.NET Core versions

For web applications using ASP.NET Core 2.x, the Community.NServiceBus.WebHost community package provides integration with the legacy WebHost.

Samples

Related Articles