Self Hosting in Azure WebJobs

Component: NServiceBus
NuGet Package NServiceBus (7.x)

This sample is compatible with Azure WebJobs SDK 3.0.

Running in development mode

  1. Start the Azure 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 StartAsync method of IJobHost is used to configure and start the endpoint:

public async Task StartAsync(CancellationToken cancellationToken)
{
    endpointConfiguration = new EndpointConfiguration("receiver");
    endpointConfiguration.SendFailedMessagesTo("error");
    endpointConfiguration.AuditProcessedMessagesTo("audit");
    endpointConfiguration.DefineCriticalErrorAction(OnCriticalError);
    endpointConfiguration.UsePersistence<InMemoryPersistence>();
    endpointConfiguration.EnableInstallers();
    endpointConfiguration.UseSerialization<NewtonsoftSerializer>();
    endpointConfiguration.EnableInstallers();

    var transportConnectionString = configuration.GetConnectionString("TransportConnectionString");

    var transport = endpointConfiguration.UseTransport<AzureStorageQueueTransport>();
    transport.ConnectionString(transportConnectionString);

    endpoint = await Endpoint.Start(endpointConfiguration)
        .ConfigureAwait(false);
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)
{
    var fatalMessage =
        $"The following critical error was encountered:\n{context.Error}\nProcess is shutting down.";
    Logger.Fatal(fatalMessage, context.Exception);

    if (Environment.UserInteractive)
    {
        // so that user can see on their screen the problem
        await Task.Delay(10_000)
            .ConfigureAwait(false);
    }

    Environment.FailFast(fatalMessage, context.Exception);

}

When the WebJob host stops, the endpoint must be shutdown to properly release all acquired resources:

public async Task StopAsync()
{
    await endpoint.Stop()
        .ConfigureAwait(false);
}

Samples


Last modified