HTTP HTTP ASP.NET dependency dependency module (MS Enterprise Library)

I followed the steps in the Microsoft Enterprise Library 5.0 documentation to create an HTTP module for entering a link to the Enterprise Library container on the pages of an ASP.NET web application.

It contains the following code (which also appears on the Internet 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 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 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;
        }
      }
    }
  }
}

There are a number of problems with this code and the instructions that came with it.

1) The instructions do not mention where to place this code. Since this is a class, I put it in the App_Code folder of my ASP.NET website project.

In fact, here are the instructions for this bit of code:

HTTP ASP.NET(, , UnityHttpModule) , PreRequestHandlerExecute , , Unity BuildUp .

2) HttpContext.Current.Application. GetContainer() , DLL- ( .NET 4.0).

3) OnPageInitComplete "context"... , , .

, ?

+4
2

, .

(2) , HttpContext.Current.Application.GetContainer() , , here.

, Unity.Web.

:

using System.Web;
using Microsoft.Practices.Unity;

namespace Unity.Web
{
  public static class HttpApplicationStateExtensions
  {
    private const string GlobalContainerKey = "EntLibContainer";

    public static IUnityContainer GetContainer(this HttpApplicationState appState)
    {
      appState.Lock();
      try
      {
        var myContainer = appState[GlobalContainerKey] as IUnityContainer;
        if (myContainer == null)
        {
          myContainer = new UnityContainer();
          appState[GlobalContainerKey] = myContainer;
        }
        return myContainer;
      }
      finally
      {
          appState.UnLock();
      }
    }
  }
}

, , , . , HTTP "" "", .

, :

protected void Application_Start(object sender, EventArgs e)
{
  Application.Lock();
  try
  {
    var myContainer = Application["EntLibContainer"] as IUnityContainer;
    if (myContainer == null)
    {
      myContainer = new UnityContainer();
      myContainer.AddExtension(new EnterpriseLibraryCoreExtension());
      // Add your own custom registrations and mappings here as required
      Application["EntLibContainer"] = myContainer;
    }
  }
  finally
  {
    Application.UnLock();
  }
}          

, global.asax, Enterprise Library, , . , LogWriter, :

using Unity.Web;

public LogWriter getLogWriter()
{
    var container = HttpContext.Current.Application.GetContainer();
    return container.Resolve<LogWriter>();
}

Unity.Web GetContainer().

+5

, MSDN, . -, , :

context.PreRequestHandlerExecute -= OnPreRequestHandlerExecute;

Init . , :

HttpApplication IHttpModule.

, :

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using Microsoft.Practices.Unity;

namespace Unity.Web
{
    /// <summary>
    /// An <see cref="IHttpModule" /> that automatically injects dependencies into ASP.NET WebForms pages.
    /// </summary>
    /// <remarks>
    /// Since the pages have already been constructed by the time the module is called, constructor injection cannot be used. However,
    /// property injection can be used instead.
    /// </remarks>
    public class UnityHttpModule : IHttpModule
    {
        private HttpApplication _context;
        private bool _disposed;

        /// <summary>
        /// Initializes a module and prepares it to handle requests.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application </param>
        public void Init(HttpApplication context)
        {
            _context = context;
            _context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
        }

        /// <summary>
        /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
        /// </summary>
        public void Dispose()
        {
            GC.SuppressFinalize(this);
            Dispose(true);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
    {
        if (_disposed)
        {
            return;
        }

        if (disposing)
        {
            if (_context != null)
            {
                _context.PreRequestHandlerExecute -= OnPreRequestHandlerExecute;
            }
        }

        _disposed = true;
    }

    /// <summary>
    /// Handles the <see cref="E:PreRequestHandlerExecute" /> event.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="eventArgs">The <see cref="EventArgs"/> instance containing the event data.</param>
    private void OnPreRequestHandlerExecute(object sender, EventArgs eventArgs)
    {
        var currentHandler = HttpContext.Current.Handler;
        if (currentHandler != null)
        {
            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;
        }
    }

    /// <summary>
    /// Handles the <see cref="E:PageInitComplete" /> event.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
    private void OnPageInitComplete(object sender, EventArgs e)
    {
        var currentPage = (Page)sender;
        var container = HttpContext.Current.Application.GetContainer();
        foreach (var c in GetControlTree(currentPage))
        {
            container.BuildUp(c.GetType(), c);
        }
    }

    /// <summary>
    /// Gets the controls in the page control tree, excluding the page itself.
    /// </summary>
    /// <param name="root">The root control.</param>
    /// <returns>The child controls of the <paramref name="root" /> control.</returns>
    private static IEnumerable<Control> GetControlTree(Control root)
    {
        foreach (Control child in root.Controls)
        {
            yield return child;
            foreach (var control in GetControlTree(child))
            {
                yield return control;
            }
        }
    }
}

, @CiaranGallagher , , :

using Unity.Web;

[Dependency]
public LogWriter Writer { get; set; }

WebForms, BuildUp , , .

+2

All Articles