是否有可能通过某种方式获得对IServiceProvider的引用或某些可以解决依赖关系的类来获得依赖?例如,当使用 UseExceptionHandler
处理异常以向客户端输出有意义的内容时,我还想做一些自定义日志记录以记录有关抛出的异常的一些内容 .
例如,假设我在ASP.net Core项目的 Startup
类中的 Configure
方法中有此代码:
app.UseExceptionHandler(
builder =>
{
builder.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "text/html";
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
// TODO Log Exception. Would like to do something like this:
// var logger = ServiceProvider.Resolve<ILogger>();
// logger.LogCritical("Unhandled Error :"error.Error.ToString());
await context.Response.WriteAsync($"<h1>Error: {error.Error.Message}</h1>").ConfigureAwait(false);
}
});
});
当我没有传递ILogger的构造函数时,如何获取ILogger的实例?
1 回答
您可以访问
builder.ApplicationServices
中的ServiceProvider
. 从那里你可以获得一个ILoggerFactory
的实例,然后为你的异常处理程序创建logger
.