Getting Started
Architecture
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Modernization
Samples

NServiceBus.Extensions.Hosting

Target Version: NServiceBus 8.x

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.

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.

Shutdown timeout

The .NET Generic Host has a configurable shutdown timeout that defaults to five seconds. During this shutdown period, NServiceBus waits for all in-flight messages to complete. To ensure the shutdown timeout is honored, all message handlers must observe the cancellation token that is available on the message handler context.

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