Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

Endpoint hosting with the Generic Host

Component: NServiceBus
NuGet Package: NServiceBus (9-pre)
This page targets a pre-release version. Pre-releases are subject to change and samples are not guaranteed to be fully functional.

The sample uses the Generic Host and the Microsoft.Extensions.Hosting.WindowsServices NuGet package to host NServiceBus as a Windows Service.

Code walk-through

The builder configures NServiceBus using the NServiceBus.Extensions.Hosting package, including the critical error action that will shut down the application or service in case of a critical error.

var endpointConfiguration = new EndpointConfiguration("Samples.Hosting.GenericHost");
var routing = endpointConfiguration.UseTransport(new LearningTransport());
endpointConfiguration.UseSerialization<SystemJsonSerializer>();
endpointConfiguration.DefineCriticalErrorAction(OnCriticalError);
endpointConfiguration.EnableInstallers();

builder.UseNServiceBus(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).ConfigureAwait(false);
    }
    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
        }
    }
}

Running the sample as a Windows Service

  • Start PowerShell with elevated permissions
  • Run dotnet publish in the directory of the sample; for example: C:\samples\generic-host
  • Run New-Service -Name WorkerTest -BinaryPathName "C:\samples\generic-host\bin\Debug\{framework}\publish\GenericHost.exe"
  • Run Start-Service WorkerTest
  • Go to the Event Viewer under Windows Logs\Applications and observe event log entries from source GenericHost with the following content:
Category: MyMessageHandler
EventId: 0

Received message #{Number}
  • Once done, run Stop-Service WorkerTest and Remove-Service WorkerTest

Related Articles


Last modified