An NServiceBus endpoint can be hosted within the generic host with the
UseNServiceBus extension method:
var host = Host.CreateDefaultBuilder()
var endpointConfiguration = new EndpointConfiguration("MyEndpoint");
// configure endpoint here
This code will register the endpoint with the hosting infrastructure and automatically start and stop it based on the host's application lifetime.
UseNServiceBus before any other service (e.g.
ConfigureWebHostDefaults) which requires access to the
IMessageSession. Incorrect usage results in a
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 (e.g.
services.AddHostedService<HostedServiceAccessingTheSession>()) or the web host configuration (e.g.
builder.ConfigureWebHostDefaults) if hosted services or controllers require access to the session.
NServiceBus endpoints hosted as part of the generic host automatically use the provided
IServiceProvider dependency injection infrastructure. Message handlers can resolve dependencies which are registered in the
UseNServiceBus automatically registers an
IMessageSession with the container which can be resolved from the
IServiceProvider or via dependency injection during runtime.
Custom dependency injection containers may be configured using
IWebHostBuilder.. NServiceBus automatically uses the host's dependency injection container. Refer to the container's documentation for further details.
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.
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.