【发布时间】:2017-01-04 15:32:09
【问题描述】:
是否有可能通过某种方式获取对 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 的实例?
【问题讨论】:
-
你使用的是什么 DI 框架?
-
我使用的是内置的asp.net core DI框架。
标签: c# dependency-injection asp.net-core .net-core