NuGet Package NServiceBus.Extensions.Hosting (1.x)
Target NServiceBus Version: 7.x


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;

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.

UseNServiceBus must be specified before any other service (e.g. ConfigureWebHostDefaults) which requires access to the IMessageSession. Incorrect usage will result in System.InvalidOperationException with the following message The message session can't be used before NServiceBus is started. Place UseNServiceBus() on the host builder before registering any hosted service (i.ex. services.AddHostedService<HostedServiceAccessingTheSession>()) or the web host configuration (i.ex. builder.ConfigureWebHostDefaults) should hosted services or controllers require access to the session.

Logging integration

NSericeBus logging will be automatically configured to use the logging configured for the generic host so 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.


Last modified