繁体   English   中英

ASP.net Core中的即时依赖注入

[英]Dependency Injection On The Fly in ASP.net Core

是否有可能通过某种方式获取对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的实例?

您可以在builder.ApplicationServices访问ServiceProvider 从那里,你optain一个实例ILoggerFactory ,然后创建logger你的异常处理程序。

app.UseExceptionHandler(
            builder =>
            {
                builder.Run(
                    async context =>
                    {
                        ...
                        var lf = builder.ApplicationServices.GetService<ILoggerFactory>();
                        var logger = lf.CreateLogger("myExceptionHandlerLogger");
                        logger.LogDebug("I am a debug message");
                        ...
                    });
            });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM