【发布时间】: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