﻿# Endpoint hosting with the Generic Host


## Code walk-through

The builder [configures NServiceBus on the generic host](/nservicebus/hosting/core-hosting.md#hosting-a-single-endpoint), including the [critical error](/nservicebus/hosting/critical-errors.md) action, which shuts down the application or service in the event of a critical error.

<!-- snippet: generic-host-nservicebus -->

```cs
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);
```

<!-- endsnippet -->

The critical error action:

<!-- snippet: generic-host-critical-error -->

```cs
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);
    }
}
```

<!-- endsnippet -->

To simulate work, a BackgroundService called `Worker` is registered as a hosted service:

<!-- snippet: generic-host-worker-registration -->

```cs
builder.Services.AddHostedService<Worker>();
```

<!-- endsnippet -->

The `IMessageSession` is injected into the `Worker` constructor, and the `Worker` sends messages when it is executed.

<!-- snippet: generic-host-worker -->

```cs
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
        }
    }
}
```

<!-- endsnippet -->

This sample focuses on Generic Host integration. For platform-specific worker service options such as Windows Services and Linux daemons, [see the Microsoft documentation](https://learn.microsoft.com/en-us/dotnet/core/extensions/workers).
