Access WebApplication/Services from program.cs later in program without DI

Viewed 33

Okay, I'm open to being told I'm approaching the problem incorrectly, so go ahead if that's the case, but I have a unhandled exception provider I'm adding to my builder.Services in program.cs, along with some data services. I can't figure out a good way to add an existing data service to the unhandled exception provider (custom logging to a db via the data service).

I had tried passing it, or using it via injection, but in the exception provider the data service keeps coming up as null in practice.

So I was thinking, is there a way to get a reference to the WebApplication that is running (the one we are running via app.Run() in Program.cs) from elsewhere in the running program.

Logically, I'd like to do something like this in the unhandled exception provider:

MyService = GetRunningApp().services.BuildServiceProvider().GetService<IMyService>();

Am I missing an easier way to do this?

1 Answers

In Blazor it's not as easy to inject the middleware for global error handling like it is with Web API (Correct me if I'm wrong!)

For Blazor I think the closest we have is the <ErrorBoundary>. Check out this solution by Alamakanambra. They provide an example on how to create a component that handles global exceptions. You can do whatever logging or handling you need in the OnErrorAsync.

protected override Task OnErrorAsync(Exception exception)
{
    receivedExceptions.Add(exception);
    return base.OnErrorAsync(exception);
}
Related