0

I have the following interface and class:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddSingleton<IExceptionManager, ExceptionManager>();
    ...
}

Now how do I inject IExceptionManager in Asp.net Core ExceptionHandler middleware ?

 app.UseExceptionHandler(a => a.Run(async context =>
            {
                var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
                var exception = exceptionHandlerPathFeature.Error;

               //how to define myExceptionManager as IExceptionManager
                await context.Response.WriteAsJsonAsync(myExceptionManager.Manage(exception));
            }));
nAviD
  • 2,784
  • 1
  • 33
  • 54
  • You _could_ use `context.RequestServices` to create it on every call, but as it's a singleton you're probably better off creating a seperate class for your middleware and injecting it into the constructor of that. – sellotape Apr 28 '21 at 12:22

1 Answers1

4

The a argument in UseExceptionHandler is an IApplicationBuilder. You can use the ApplicationServices property to retrieve services, eg:

app.UseExceptionHandler(a => a.Run(async context =>
{
    var myExceptionManager =a.ApplicationServices.GetRequiredService< IExceptionManager>();
                
    var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
    var exception = exceptionHandlerPathFeature.Error;

    //how to define myExceptionManager as IExceptionManager
    await context.Response.WriteAsJsonAsync(myExceptionManager.Manage(exception));
}));
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • Thank you for your answer . I wonder why it does not hit this function when I send an object with invalid validation. and I receive the following error in client without the Run function being exceuted : {"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-f7bdad2ec3c0424f8fdf10f5a389d085-6e8c1713f1ce8147-00","errors":{"Name":["The field Name is required"]}} – nAviD May 01 '21 at 09:41
  • I added another question would you please answer it too : https://stackoverflow.com/questions/67344945/useexceptionhandler-is-not-working-with-validation-errors – nAviD May 01 '21 at 09:56