Share via


ASP.NET Application State Extension

You can use an HTTP module, an extension to the ASP.NET HttpApplicationState class, and code in Global.asax to force ASP.NET to automatically inject dependent objects at every page request, as discussed in the topic ASP.NET Web Forms Applications.

The following shows a suitable implementation of an application state extension that exposes a static GetContainer method. The method creates a new Unity container in the Application state if one does not already exist, or returns a reference to the existing instance.

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();
      }
    }
  }
}
'Usage
Imports System.Web
Imports Microsoft.Practices.Unity

Namespace Unity.Web

  Public Module HttpApplicationStateExtensions

    Private Const GlobalContainerKey As String = "EntLibContainer"

    <System.Runtime.CompilerServices.Extension> _
    Public Shared Function GetContainer(appState As HttpApplicationState) As IUnityContainer
      appState.Lock()
      Try
        Dim myContainer = TryCast(appState(GlobalContainerKey), IUnityContainer)
        If myContainer Is Nothing Then
          myContainer = New UnityContainer()
          appState(GlobalContainerKey) = myContainer
        End If
        Return myContainer
      Finally
        appState.UnLock()
      End Try
    End Function

  End Module

End Namespace