29

All implementation of IHttpModule I've seen looks following:

class HttpCompressionModule : IHttpModule
{
  public void Init(HttpApplication application)
  {
    application.SomeEvent += OnSomeEvent;
  }

  private void OnSomeEvent(Object source, EventArgs e)
  {
    // ...
  }

  public void Dispose() 
  {
    // nothing here !!!
  } 
}

I am wondering why is the Dispose method always empty? Shouldn't we unsubscribe the event which we subscribe in the Init method?

Bill the Lizard
  • 369,957
  • 201
  • 546
  • 842
Jakub Šturc
  • 32,938
  • 24
  • 85
  • 107

2 Answers2

28

The lifecycle of an HttpModule is tightly integrated with the lifecycle of an HttpApplication. Instances of HttpModule are generated when the application is started and destroyed when the application is disposed of.

In this case there is no point in unsubscribing from the event because the publisher (HttpApplication) is being disposed of anyway. Of course, in a situation where the publisher wasn't being disposed of, unhooking the event handler would be the right thing to do.

Matt B
  • 7,624
  • 2
  • 39
  • 57
  • 6
    I tried unregistering on Dispose and got InvalidOperationException with the message "Event handlers can only be bound to HttpApplication events during IHttpModule initialization." – angularsen Oct 11 '12 at 08:27
5

The dispose method won't be empty if you need to instantiate IDisposable objects inside your module.

class HttpCompressionModule : IHttpModule
{
  private IDisposalbe _myResource;

  public void Init(HttpApplication application)
  {
    _myResource = new MyDisposableResource();
    application.SomeEvent += OnSomeEvent;
  }

  private void OnSomeEvent(Object source, EventArgs e)
  {
    // ...
    myResource.DoSomething();
  }

  public void Dispose() 
  {
    _myResource.Dispose();
  } 
}
Thomas Langston
  • 3,688
  • 1
  • 22
  • 36