Code walk-through
The builder configures NServiceBus on the generic host, including the critical error action, which shuts down the application or service in the event of a critical error.
var endpointConfiguration = new EndpointConfiguration("Samples.Hosting.GenericHost");
endpointConfiguration.UseTransport(new LearningTransport());
endpointConfiguration.UseSerialization<SystemJsonSerializer>();
endpointConfiguration.DefineCriticalErrorAction(OnCriticalError);
// It is recommended to run least privilege and only run installers during deployment.
// This also reduces startup time / time to first message.
var isDevelopment = Debugger.IsAttached;
var isSetup = args.Contains("--setup");
if (isSetup)
{
// Provision resources like transport queue creation and persister schemas
builder.Services.AddNServiceBusInstallers(configure =>
configure.ShutdownBehavior = InstallersShutdownBehavior.StopApplication);
}
else if (isDevelopment)
{
endpointConfiguration.EnableInstallers();
}
builder.Services.AddNServiceBusEndpoint(endpointConfiguration);
The critical error action:
static async Task OnCriticalError(ICriticalErrorContext context, CancellationToken cancellationToken)
{
var fatalMessage =
$"The following critical error was encountered:{Environment.NewLine}{context.Error}{Environment.NewLine}Process is shutting down. StackTrace: {Environment.NewLine}{context.Exception.StackTrace}";
try
{
await context.Stop(cancellationToken);
}
finally
{
Environment.FailFast(fatalMessage, context.Exception);
}
}
To simulate work, a BackgroundService called Worker is registered as a hosted service:
builder.Services.AddHostedService<Worker>();
The IMessageSession is injected into the Worker constructor, and the Worker sends messages when it is executed.
class Worker(IMessageSession messageSession) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
try
{
var number = 0;
while (!cancellationToken.IsCancellationRequested)
{
await messageSession.SendLocal(new MyMessage { Number = number++ }, cancellationToken);
await Task.Delay(1000, cancellationToken);
}
}
catch (OperationCanceledException)
{
// graceful shutdown
}
}
}
This sample focuses on Generic Host integration. For platform-specific worker service options such as Windows Services and Linux daemons, see the Microsoft documentation.