【问题标题】:InRequestScope fails to work in context of ExceptionLoggerInRequestScope 无法在 ExceptionLogger 的上下文中工作
【发布时间】:2014-11-10 08:35:02
【问题描述】:

我有一个自定义的 Web API ExceptionLogger,它像这样添加到 WebApiConfig 中:

config.Services.Add(typeof(IExceptionLogger), new CustomExceptionLogger(kernel.Get<ILoggerFactory>());

CustomExceptionLogger 是:

public class CustomExceptionLogger : ExceptionLogger
{
    private readonly ILoggerFactory _logFactory;

    public CustomExceptionLogger(ILoggerFactory log)
    {
        _logFactory = log;
    }

    public override void Log(ExceptionLoggerContext context)
    {
        var log = _logFactory.Create();
        log.LogError("Unhandled exception: {0}",
            context.Exception);
    }
}

Ninject 绑定是:

Bind<ILogger>().ToMethod(CreateLogger)
    .InRequestScope();
Bind<ILoggerFactory>().ToFactory();

我正在使用 Ninject.Extensions.Factory 扩展。 ILoggerFactory 接口是:

public interface ILoggerFactory
{
    ILogger Create();
}

当调用 Log() 时,我希望 ILoggerFactory 返回一个 ILogger 实例,该实例的范围是请求。但是,在这种情况下,我收到了一个新的 ILogger 实例,该实例与其他使用 ILoggerFactory 的其他实例不同。这似乎是因为 HttpContext.Current 在 Log() 方法中是 null。尽管 ExceptionLoggerContext 对象包含一个 Request 对象(所以这个方法有一些请求上下文,只是不是实际的 HttpContext)。

我正在使用 Web API 2.2/Ninject 3.2.2 的 IIS/Web 主机版本。

在这种情况下如何让 InRequestScope() 正常工作?

【问题讨论】:

    标签: c# asp.net-web-api ninject asp.net-web-api2 ninject.web


    【解决方案1】:

    事实证明,这种行为是以下原因造成的:

    Why is HttpContext.Current null after await?

    在 web.config 中将 targetFramework="4.5" 添加到 httpRuntime 会导致 HttpContext 在此方法中不再为空。因此,这修复了 InRequestScope() 的行为。

    <system.web>
       <httpRuntime targetFramework="4.5" />
    </system.web>
    

    【讨论】:

      猜你喜欢
      • 2019-02-10
      • 1970-01-01
      • 2023-01-28
      • 2016-08-16
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      相关资源
      最近更新 更多