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.
Call UseNServiceBus
before registering any component that needs IMessageSession
. Placing it later can cause a System.
:
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.
) or the web host configuration (e.g.AddHostedService <HostedServiceAccessingTheSession>() builder.
) if hosted services or controllers require access to the session.ConfigureWebHostDefaults
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.
Do not use NServiceBus.Extensions.Logging or NServiceBus.MicrosoftLogging.Hosting with NServiceBus.
.
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.
. 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 .
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();