2

I have a custom Web API ExceptionLogger which is added in WebApiConfig like so:

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

CustomExceptionLogger is:

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 bindings are:

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

I am using the Ninject.Extensions.Factory extension. The ILoggerFactory interface is:

public interface ILoggerFactory
{
    ILogger Create();
}

When Log() is called, I want the ILoggerFactory to return an instance of ILogger which is scoped to the request. However, in this case, I receive back a new ILogger instance that is different to the other instance which has been used elsewhere where ILoggerFactory is used. This seems to be due to HttpContext.Current being null in the Log() method. This is despite the fact that the ExceptionLoggerContext object contains a Request object (so this method has some context of request, just not the actual HttpContext).

I am using IIS/Web Host versions of Web API 2.2/Ninject 3.2.2.

How can I get InRequestScope() to work correctly in this case?

1 Answers1

2

It turns out this behaviour was a consequence of the following:

Why is HttpContext.Current null after await?

Adding targetFramework="4.5" to httpRuntime in web.config caused HttpContext to no longer be null in this method. This consequently fixed the behaviour of InRequestScope().

<system.web>
   <httpRuntime targetFramework="4.5" />
</system.web>
Community
  • 1
  • 1