NServiceBus icon indicating copy to clipboard operation
NServiceBus copied to clipboard

DefineCriticalErrorAction access to IServiceProvider

Open dnv-kimbell opened this issue 1 year ago • 3 comments

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

dnv-kimbell avatar May 24 '24 06:05 dnv-kimbell

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

bording avatar May 24 '24 19:05 bording

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.

dnv-kimbell avatar May 27 '24 05:05 dnv-kimbell

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

johnsimons avatar May 29 '24 00:05 johnsimons