title: "HttpContext.Current.Session" vs Global.asax "this.Session"
body: <p>Recently, while working on some code for an ASP.NET project at work. We needed a tracking util to take basic metrics on user activity (page hit count etc) we would track them in <a href="http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.aspx" rel="noreferrer"><code>Session</code></a>, then save the data to DB via <code>Session_End</code> in <a href="http://msdn.microsoft.com/en-us/library/1xaas8a2.aspx" rel="noreferrer"><code>Global.asax</code></a>.</p>
  
  <p>I began hacking away, the initial code worked fine, updating the DB on each page load. I wanted to remove this DB hit on each request though and just rely on <code>Session_End</code> to store all the data.</p>
  
  <p>All of the tracking code is encapsulated in the <code>Tracker</code> class, including properties that essentially wrap the Session variables.</p>
  
  <p><strong>The problem</strong>  is that when I executed <code>Tracker.Log()</code> in the <code>Session_End</code> method, the <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcontext.current.aspx" rel="noreferrer"><code>HttpContext.Current.Session</code></a> in the Tracker code was failing with a <a href="http://msdn.microsoft.com/en-us/library/system.nullreferenceexception.aspx" rel="noreferrer"><code>NullReferenceException</code></a>. Now, this makes sense since <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcontext.aspx" rel="noreferrer"><code>HttpContext</code></a> always relates to the <strong>current</strong> request, and of course in <code>Session_End</code>, there is no request.</p>
  
  <p>I know that <code>Global.asax</code> has a <code>Session</code> property which returns a <code>HttpSessionState</code> that actually seems to work fine (I ended up injecting it in to the tracker)..</p>
  
  <p><strong>But I am curious, how the hell can I get the same reference to the <code>HttpSessionState</code> object used by <code>Global.asax</code> from <em>outside</em> of <code>Global.asax</code>?</strong></p>
  
  <p>Thanks in advance guys, I appreciate the input. :)</p>