现有中间件中的 DI

DI in an existing middleware

我有以下界面和class:

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

现在如何在 Asp.net Core ExceptionHandler 中间件中注入 IExceptionManager?

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

a参数UseExceptionHandler is an IApplicationBuilder. You can use the ApplicationServices属性获取服务,如:

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