【问题标题】:Dependency Injection On The Fly in ASP.net CoreASP.net Core 中的动态依赖注入
【发布时间】: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


【解决方案1】:

您可以在builder.ApplicationServices 中访问ServiceProvider。从那里你选择一个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");
                        ...
                    });
            });

【讨论】:

  • 不应该使用builder.ApplicationServices。您可以将方法定义为Configure(IApplicationBuilder, IHostingEnvironment, ILoggerFactory)
猜你喜欢
  • 2018-01-16
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多