0
public class HandlerFactory : IHttpHandlerFactory
{
    public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
    {
        // lots of code
    }

    public void ReleaseHandler(IHttpHandler handler)
    {
        // HttpContext.Current is always null here.
    }
}

How can I make HttpContext.Current available (or use alternative approach to store per-request variables such that they can be retrieved in ReleaseHandler)?

QrystaL
  • 4,886
  • 2
  • 24
  • 28

1 Answers1

0

After looking at the System.Web assembly in .NET Reflector, it appears that ReleaseHandler may be called outside of the lifecycle of a request, which means that the concept of having HttpContext.Current is not applicable. However, there are a couple of things I could suggest:

  1. If you control the implementation of the handler that GetHandler returns, you could add public or internal members to it to represent the specific data you are looking to use in ReleaseHandler.

    public class MyHandler : IHttpHandler
    {
        /* Normal IHttpHandler implementation */
    
        public string ThingIWantToUseLater { get;set; }
    }
    

    Then in your handler factory:

    public class HandlerFactory : IHttpHandlerFactory
    {
        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            // lots of code
            return new MyHandler()
            {
                    ThingIWantToUseLater = "some value"
            };
        }
    
        public void ReleaseHandler(IHttpHandler handler)
        {
             if (handler is MyHandler)
             {
                  var myHandler = handler as MyHandler;
                  // do things with myHandler.ThingIWantToUseLater
             }
        }
    }
    
  2. Could use the above approach and just slip the actual HttpContext in your implementation of the handler. I think that could lead to weird architectural places, but it's your call.

Daniel James
  • 125
  • 1
  • 8