【问题标题】:DI in an existing middleware现有中间件中的 DI
【发布时间】:2021-04-28 12:12:40
【问题描述】:

我有以下接口和类:

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

【问题讨论】:

  • 可以在每次调用时使用context.RequestServices 创建它,但由于它是一个单例,您最好为中间件创建一个单独的类并将其注入它的构造函数。

标签: c# asp.net-core asp.net-web-api dependency-injection middleware


【解决方案1】:

UseExceptionHandler 中的 a 参数是 IApplicationBuilder。您可以使用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));
}));

【讨论】:

  • 感谢您的回答。我想知道为什么当我发送一个无效验证的对象时它没有命中这个函数。我在没有执行 Run 函数的情况下在客户端收到以下错误:{"type":"tools.ietf.org/html/… or more validation errors occurred.","status":400,"traceId":"00-f7bdad2ec3c0424f8fdf10f5a389d085-6e8c1713f1ce8147-00 ","errors":{"Name":["字段名称为必填项"]}}
  • 我添加了另一个问题,请您也回答一下:stackoverflow.com/questions/67344945/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-11
  • 1970-01-01
  • 2014-07-09
  • 2015-10-09
  • 2022-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多