How to dispose IHttpModule correctly?

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?


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.


如果需要在模块中实例化IDisposable对象,则dispose方法将不会为空。

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();
  } 
}
链接地址: http://www.djcxy.com/p/43780.html

上一篇: 帮助从HttpContext.InputStream中读取JSON

下一篇: 如何正确处理IHttpModule?