title: ASP.NET MVC Dependency Injection with UnityContainer Session State
body: <p>I have a asp.net mvc web site where I make use of the Dependency Injections features of the "<code>Micorosoft.Practices.Unity</code>" and "<code>Microsoft.Practices.ObjectBuilder2</code>".  This all works great by injected my objects into my controllers constructors.</p>
  
  <p>The problem is that I am having difficulty in clearing this session when a user leaves the browser or wants to log off.  All the values remain persisted in the objects.  How can I destory the container which is created in the global.asax on either <code>Session_End()</code> or by a user click and taken care by a controller action.  </p>
  
  <p>Below is some sample code.</p>
  
  <p><code>Global.asax</code> - Performed from <code>Session_start</code>:</p>
  
  <pre><code>protected static void RegisterDependencies()
  {
      IUnityContainer container = new UnityContainer();
  
      container.RegisterType&lt;DataStore, DataStore&gt;(new SessionLifetimeManager&lt;DataStore&gt;());
      container.RegisterType&lt;IMotorRepository, MotorRepository&gt;(new SessionLifetimeManager&lt;IMotorRepository&gt;());
      container.RegisterType&lt;ICoverRepository, CoverRepository&gt;(new SessionLifetimeManager&lt;ICoverRepository&gt;());
      container.RegisterType&lt;IDriverRepository, DriverRepository&gt;(new SessionLifetimeManager&lt;IDriverRepository&gt;());
      container.RegisterType&lt;IVehicleRepository, VehicleRepository&gt;(new SessionLifetimeManager&lt;IVehicleRepository&gt;());
      container.RegisterType&lt;ICodeValueRepository, CodeValueRepository&gt;(new SessionLifetimeManager&lt;ICodeValueRepository&gt;());
  
      ControllerBuilder.Current.SetControllerFactory(
          new UnityControllerFactory(container)
      );
  }
  </code></pre>
  
  <p><code>SessionLifeTimeManager</code>:</p>
  
  <pre><code>public class SessionLifetimeManager&lt;T&gt; : LifetimeManager, IDisposable
  {
      public override object GetValue()
      {
          return HttpContext.Current.Session[typeof(T).AssemblyQualifiedName];
      }
      public override void RemoveValue()
      {
          HttpContext.Current.Session.Remove(typeof(T).AssemblyQualifiedName);
      }
      public override void SetValue(object newValue)
      {
          HttpContext.Current.Session[typeof(T).AssemblyQualifiedName] = newValue;
      }
      public void Dispose()
      {
          RemoveValue();
      }
  }
  </code></pre>