# 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. ```cs var endpointConfiguration = new EndpointConfiguration("Samples.Hosting.GenericHost"); endpointConfiguration.UseTransport(new LearningTransport()); endpointConfiguration.UseSerialization(); 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 await NServiceBus.Installation.Installer.Setup(endpointConfiguration); return; // Exit application } else if (isDevelopment) { endpointConfiguration.EnableInstallers(); } builder.UseNServiceBus(endpointConfiguration); ``` The critical error action: ```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); } } ``` To simulate work, a BackgroundService called `Worker` is registered as a hosted service: ```cs builder.Services.AddHostedService(); ``` The `IMessageSession` is injected into the `Worker` constructor, and the `Worker` sends messages when it is executed. ```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 } } } ``` 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).