Getting Started
Architecture
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

NServiceBus.Extensions.Hosting

NuGet Package: NServiceBus.Extensions.Hosting (1.x)
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 within the generic host with 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 code will register the endpoint with the hosting infrastructure and automatically start and stop it based on the host's application lifetime.

Logging integration

NServiceBus logging is automatically configured to use the logging configured for the generic host; no NServiceBus specific logging configuration is needed.

Dependency injection integration

NServiceBus endpoints hosted as part of the generic host automatically use the provided IServiceCollection and IServiceProvider dependency injection infrastructure. Message handlers can resolve dependencies which are registered in the IServiceCollection.

UseNServiceBus automatically registers an IMessageSession with the container which can be resolved from the IServiceProvider or via dependency injection during runtime.

Configure custom containers

Custom dependency injection containers may be configured using IWebHostBuilder.UseServiceProviderFactory. NServiceBus automatically uses the host's dependency injection container. Refer to the container's documentation for further details.

Stopping the endpoint

When using the generic host, the IEndpointInstance interface to stop the endpoint is not directly exposed. To stop the endpoint, use the IApplicationLifetime interface to gracefully stop the NServiceBus endpoint and other hosted services. See the generic host application lifetime documentation for further information.

Installers

It is not recommended to always run the NServiceBus installers by invoking .EnableInstallers() as this delays startup time and might require more permissions.

Instead of invoking host.

Example:

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