C# InRequestScope在ExceptionLogger上下文中无法工作
我有一个自定义Web API ExceptionLogger,它添加在WebApiConfig中,如下所示:C# InRequestScope在ExceptionLogger上下文中无法工作,c#,asp.net-web-api,ninject,asp.net-web-api2,ninject.web,C#,Asp.net Web Api,Ninject,Asp.net Web Api2,Ninject.web,我有一个自定义Web API ExceptionLogger,它添加在WebApiConfig中,如下所示: config.Services.Add(typeof(IExceptionLogger), new CustomExceptionLogger(kernel.Get<ILoggerFactory>()); Ninject绑定是: Bind<ILogger>().ToMethod(CreateLogger) .InRequestScope(); Bind&
config.Services.Add(typeof(IExceptionLogger), new CustomExceptionLogger(kernel.Get<ILoggerFactory>());
Ninject绑定是:
Bind<ILogger>().ToMethod(CreateLogger)
.InRequestScope();
Bind<ILoggerFactory>().ToFactory();
调用Log()时,我希望ILogger工厂返回一个ILogger实例,该实例的作用域为请求。但是,在本例中,我收到了一个新的ILogger实例,它与在其他地方使用ILogger Factory的其他实例不同。这似乎是由于Log()方法中的HttpContext.Current
为null
。尽管ExceptionLoggerContext对象包含一个请求对象(因此此方法具有一些请求上下文,而不是实际的HttpContext),但仍然存在这种情况
我使用的是Web API 2.2/Ninject 3.2.2的IIS/Web主机版本
在这种情况下,如何使InRequestScope()正常工作?事实证明,这种行为是由以下原因造成的: 将
targetFramework=“4.5”
添加到web.config中的httpRuntime会导致HttpContext在此方法中不再为null。这因此固定了InRequestScope()的行为
Bind<ILogger>().ToMethod(CreateLogger)
.InRequestScope();
Bind<ILoggerFactory>().ToFactory();
public interface ILoggerFactory
{
ILogger Create();
}
<system.web>
<httpRuntime targetFramework="4.5" />
</system.web>