locked
Error in HTTP Module example code... RRS feed

  • Question

  • User1810140830 posted

    Wanted to add DI to my asp.net project, was following PnP's HTTModule example here:

    http://msdn.microsoft.com/en-us/library/ff664534(v=PandP.50).aspx

    In it, they remove the listener to OnPreRequestHandlerExecute after page init completes. Buty they simply refrence it as:

     context.PreRequestHandlerExecute -= OnPreRequestHandlerExecute;

    There's no such context in OnPageInitComplete. What's the best way for getting a reference to the HttpApplication to remove this listener? Can I skip it, or will I get a memory leak by ignoring it?

    The full code is here:

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.UI;
    using Microsoft.Practices.Unity;
    
    namespace Unity.Web
    {
      public class UnityHttpModule : IHttpModule
      {
        public void Init(HttpApplication context)
        {
          context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
        }
    
        public void Dispose() { }
    
        private void OnPreRequestHandlerExecute(object sender, EventArgs e)
        {
          IHttpHandler currentHandler = HttpContext.Current.Handler;
          HttpContext.Current.Application.GetContainer().BuildUp(
                              currentHandler.GetType(), currentHandler);
    
          // User Controls are ready to be built up after page initialization is complete
          var currentPage = HttpContext.Current.Handler as Page;
          if (currentPage != null)
          {
            currentPage.InitComplete += OnPageInitComplete;
          }
        }
    
        // Build up each control in the page's control tree
        private void OnPageInitComplete(object sender, EventArgs e)
        {
          var currentPage = (Page)sender;
          IUnityContainer container = HttpContext.Current.Application.GetContainer();
          foreach (Control c in GetControlTree(currentPage))
          {
            container.BuildUp(c.GetType(), c);
          }
          context.PreRequestHandlerExecute -= OnPreRequestHandlerExecute;
        }
    
        // Get the controls in the page's control tree excluding the page itself
        private IEnumerable<Control> GetControlTree(Control root)
        {
          foreach (Control child in root.Controls)
          {
            yield return child;
            foreach (Control c in GetControlTree(child))
            {
              yield return c;
            }
          }
        }
      }
    }
    Saturday, November 5, 2011 12:55 PM

Answers

  • User1622957740 posted

    Use HttpContext.Current.ApplicationInstance to get a reference HttpApplication.

    +++ Rick ---

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, November 14, 2011 10:41 PM