Getting Started
Architecture
NServiceBus
Transports
Persistence
Hosting
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Modernization
Samples

NServiceBus.Extensions.Hosting

Target Version: NServiceBus 7.x
Standard support for version 7.x of NServiceBus has expired. For more information see our Support Policy.

Configuration

An NServiceBus endpoint can be hosted in the .NET Generic Host using the UseNServiceBus extension method:

var host = Host.CreateDefaultBuilder()
    .UseNServiceBus(hostBuilderContext =>
    {
        var endpointConfiguration = new EndpointConfiguration("MyEndpoint");
        // configure endpoint here
        return endpointConfiguration;
    })
    .Build();

await host.RunAsync();

This registers the endpoint with the hosting infrastructure and starts/stops it automatically with the application's lifetime.

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.

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();

The Generic Host automatically loads configuration from:

  • appsettings.json
  • appsettings.{Environment}.json (for example, appsettings.Development.json)
  • Environment variables

No additional setup is required to enable these sources.

Connection strings

Transport and persistence connection strings are typically stored in the ConnectionStrings section of appsettings.json:

{
  "ConnectionStrings": {
    "Transport": "host=localhost;username=guest;password=guest"
  }
}

Read them with IConfiguration.GetConnectionString("Transport") and pass the result to the transport configuration:

var host = Host.CreateDefaultBuilder()
    .UseNServiceBus(ctx =>
    {
        var transportConnectionString = ctx.Configuration.GetConnectionString("Transport");

        var endpointConfiguration = new EndpointConfiguration("MyEndpoint");

        // Pass transportConnectionString to the transport, for example:
        //   var transport = endpointConfiguration.UseTransport<YourTransport>();
        //   transport.ConnectionString(transportConnectionString);
        _ = transportConnectionString;

        return endpointConfiguration;
    })
    .Build();

await host.RunAsync();

The exact transport API depends on the transport package in use; see the documentation for the transport being configured.

Strongly-typed settings

For more complex configuration, bind a settings class to a configuration section using the .NET options pattern and use the bound values during endpoint setup:

{
  "NServiceBus": {
    "EndpointName": "Sales",
    "MaxConcurrency": 8
  }
}
class EndpointSettings
{
    public string EndpointName { get; set; } = "MyEndpoint";
    public int MaxConcurrency { get; set; } = 4;
}

async Task UseOptionsPattern()
{
    var host = Host.CreateDefaultBuilder()
        .UseNServiceBus(ctx =>
        {
            var settings = ctx.Configuration
                .GetSection("NServiceBus")
                .Get<EndpointSettings>() ?? new EndpointSettings();

            var endpointConfiguration = new EndpointConfiguration(settings.EndpointName);
            endpointConfiguration.LimitMessageProcessingConcurrencyTo(settings.MaxConcurrency);

            return endpointConfiguration;
        })
        .Build();

    await host.RunAsync();
}

Other configuration sources

Because the entry point is IConfiguration, any configuration provider works without additional integration, including User Secrets, Azure Key Vault, and AWS Systems Manager Parameter Store. See the .NET configuration providers documentation for the full list.

Azure Functions and other hosts

The same IConfiguration-based pattern applies when hosting in Azure Functions. ServiceBusTriggeredEndpointConfiguration reads values from the Functions host's IConfiguration (and falls back to environment variables), so settings flow through local.settings.json in development and through Function app settings in Azure. See the Azure Functions configuration reference for the keys recognized by the Azure Service Bus integration, including connection-string and identity-based connection options.

When connecting endpoints across transports using the NServiceBus.Transport.Bridge, the same HostBuilderContext.Configuration access is available during bridge setup; see Bridge configuration.

Logging integration

NServiceBus logging is automatically wired to the host's logging pipeline. No NServiceBus-specific logging configuration is required. See .NET logging and the Generic Host.

Dependency injection integration

When hosted in the Generic Host, NServiceBus uses the application's IServiceCollection / IServiceProvider. Message handlers can resolve services registered in IServiceCollection.

UseNServiceBus also registers an IMessageSession that can be resolved from the container or injected where needed at runtime.

Configure custom containers

To use a third-party container, configure it with HostBuilder.UseServiceProviderFactory(...). NServiceBus will automatically use the host’s container. Refer to your container’s documentation for details.

Stopping the endpoint

With the Generic Host, the IEndpointInstance used to stop the endpoint is not exposed directly. To shut down gracefully, request application shutdown via IHostApplicationLifetime. See Generic Host application lifetime for more information.

Installers

Avoid always running NServiceBus installers via .EnableInstallers() as it adds startup time and may require elevated permissions.

Instead, run installers explicitly in a dedicated “setup” mode:

var isSetup = args.Contains("-s") || args.Contains("/s");

if (isSetup)
{
    // Installers are useful in development. Consider disabling in production.
    // https://docs.particular.net/nservicebus/operations/installers
    // endpointConfiguration.EnableInstallers();

    await Installer.Setup(endpointConfiguration);
    return;
}

// Continue and eventually invoke:
// await host.RunAsync();

Samples