Getting Started
Architecture
Transports
Persistence
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.

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