Particular / NServiceBus

Build, version, and monitor better microservices with the most powerful service platform for .NET
https://particular.net/nservicebus/
Other
2.07k stars 648 forks source link

DefineCriticalErrorAction access to IServiceProvider #7039

Open dnv-kimbell opened 3 months ago

dnv-kimbell commented 3 months ago

Describe the feature.

We are implementing DefineCriticalErrorAction() to shut down the application. In your documentation there is a mention of IHostApplicationLifetime.Stop, but the challenge is that ICriticalErrorContext doesn't give us access to an IServiceProvider where we can get access to IHostApplicationLifetime.

Our workaround is to have a hosted services that polls a static property where DefineCriticalErrorAction() can set the ICriticalErrorContext. Not pretty.

Additional Context

No response

bording commented 3 months ago

@dnv-kimbell

It is already possible to use IHostApplicationLifetime methods from your critical error action. For example, here's one way you can do that:

var builder = Host.CreateApplicationBuilder(args);

IHostApplicationLifetime lifetime = null;

var endpointConfiguration = new EndpointConfiguration("example");
var routing = endpointConfiguration.UseTransport(new LearningTransport());
endpointConfiguration.UseSerialization<SystemJsonSerializer>();
endpointConfiguration.DefineCriticalErrorAction((context, cancellationToken) => OnCriticalError(context, cancellationToken, lifetime));

builder.UseNServiceBus(endpointConfiguration);

var app = builder.Build();
lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
app.Run();

static Task OnCriticalError(ICriticalErrorContext context, CancellationToken cancellationToken, IHostApplicationLifetime lifetime)
{
    lifetime.StopApplication();

    return Task.CompletedTask;
}
dnv-kimbell commented 3 months ago

We have an application portfolio spanning 150 repos containing deployable code; mixture of ASP.NET and Windows Services. In order to keep this maintainable and consistent, we have created a highly opinionated framework on top of ASP.NET. This sets up authentication, logging, metrics, and a bunch of other things. When using external libraries such as NServiceBus, Quartz or GraphQL, we wrap them in a system that allows us to easily set them up with the rest of the system.

Your example takes advantage of C# closures and the fact that everything is in the same file. This is not something our applications can take advantage.

johnsimons commented 2 months ago

Hi @dnv-kimbell

Thanks for providing more context to this feature request. We acknowledge that, currently, the API is not ideal for your scenario. We will take this into consideration in an upcoming enhancement release.

Regards John