﻿# NServiceBus in ASP.NET

<!-- Version variant: extensions.hosting_1; default: [/nservicebus/hosting/asp-net.md](/nservicebus/hosting/asp-net.md) -->


NServiceBus easily integrates with [ASP.NET Core](https://asp.net) applications.

## Minimal APIs

ASP.NET 6 introduced a new hosting API with the [ASP.NET minimal APIs](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-6.0). The [NServiceBus.Extensions.Hosting package](/nservicebus/hosting/extensions-hosting.md) is fully compatible with the minimal API's `WebApplication` host:

<!-- snippet: asp-net-minimal-host-endpoint -->

```cs
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();
```

<!-- endsnippet -->

## Generic Host

Starting with ASP.NET 3, the [NServiceBus Generic Host support](/nservicebus/hosting/extensions-hosting.md) provides integration with ASP.NET Core applications:

<!-- snippet: asp-net-generic-host-endpoint -->

```cs
var builder = Host.CreateDefaultBuilder()
    .UseNServiceBus(context =>
    {
        var endpointConfiguration = new EndpointConfiguration("MyWebAppEndpoint");

        // configure the endpoint

        return endpointConfiguration;
    })
    .ConfigureWebHostDefaults(webHost => webHost.UseStartup<Startup>())
    .Build();

builder.Run();
```

<!-- endsnippet -->

## Reading application settings

NServiceBus is configured in code. Values such as endpoint names, connection strings, and feature flags can be sourced from `appsettings.json` or any other configuration provider by reading them via `IConfiguration` and passing them to the NServiceBus configuration API.

When using the Minimal API host, read configuration via `builder.Configuration`:

<!-- snippet: asp-net-minimal-host-appsettings -->

```cs
var builder = WebApplication.CreateBuilder();

var endpointName = builder.Configuration.GetValue<string>("NServiceBus:EndpointName")
    ?? "MyWebAppEndpoint";

builder.Host.UseNServiceBus(context =>
{
    var endpointConfiguration = new EndpointConfiguration(endpointName);
    // configure endpoint, passing values from context.Configuration as needed
    return endpointConfiguration;
});

var host = builder.Build();

// further ASP.NET configuration

host.Run();
```

<!-- endsnippet -->

When using the Generic Host, read configuration via the `HostBuilderContext` (or `hostBuilder.Configuration`):

<!-- snippet: extensions-host-appsettings -->

```cs
var host = Host.CreateDefaultBuilder()
    .UseNServiceBus(ctx =>
    {
        var endpointName = ctx.Configuration.GetValue<string>("NServiceBus:EndpointName")
            ?? "MyEndpoint";

        var endpointConfiguration = new EndpointConfiguration(endpointName);
        // configure endpoint, passing values from ctx.Configuration as needed
        return endpointConfiguration;
    })
    .Build();

await host.RunAsync();
```

<!-- endsnippet -->

Both `WebApplication.CreateBuilder()` and `Host.CreateApplicationBuilder()` automatically load configuration from:

- `appsettings.json`
- `appsettings.{Environment}.json` (for example, `appsettings.Development.json`)
- Environment variables

No additional setup is required to enable these sources. See [Reading application settings](/nservicebus/hosting/extensions-hosting.md#reading-application-settings) for guidance on connection strings, the options pattern, and other configuration providers.

## Dependency injection

Messages can be sent with NServiceBus using the `IMessageSession` API, which is available via the dependency injection container.

### Web API controllers

<!-- snippet: web-api-usage -->

```cs
[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");
    }
}
```

<!-- endsnippet -->

### MVC controllers

<!-- snippet: mvc-controller-usage -->

```cs
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();
    }
}
```

<!-- endsnippet -->

### Razor Pages

<!-- snippet: razor-page-usage -->

```cs
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");
    }
}
```

<!-- endsnippet -->

## Older ASP.NET Core versions

For web applications using ASP.NET Core 2.x, the [Community.NServiceBus.WebHost](https://github.com/timbussmann/Community.NServiceBus.WebHost) community package provides integration with the legacy WebHost.
