Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

Self-Hosting in Azure WebJobs

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.

This sample is compatible with Azure WebJobs SDK 3.0.

Running in development mode

  1. Start the Azurite Storage Emulator.
  2. Run the solution.

Code walk-through

This sample contains one project:

  • Receiver: A self-hosted endpoint running in a continuous WebJob.

Receiver

The receiver uses the self-hosting capability to start an end endpoint inside a continuously running WebJob.

The UseNServiceBus method of NServiceBus.Extensions.Hosting is used to configure and start the endpoint:

hostBuilder.UseNServiceBus(ctx =>
{
    var endpointConfiguration = new EndpointConfiguration("receiver");
    endpointConfiguration.DefineCriticalErrorAction(OnCriticalError);
    endpointConfiguration.UsePersistence<NonDurablePersistence>();
    endpointConfiguration.UseSerialization<SystemJsonSerializer>();
    endpointConfiguration.EnableInstallers();

    var transportConnectionString = ctx.Configuration.GetConnectionString("TransportConnectionString");
    endpointConfiguration.UseTransport(new AzureStorageQueueTransport(transportConnectionString));

    return endpointConfiguration;
});
If dependencies need to be shared between the service collection and NServiceBus infrastructure, such as message handlers, see the ASP.NET Core sample.

A critical error action must be defined to restart the host when a critical error is raised:

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);
    }
}

When the WebJob host stops, the endpoint endpoint is automatically stopped with the host. This is taken care off by the hosting extension.

Samples


Last modified