Programmatically register HttpModules at runtime

It has to be done at just the right
time in the HttpApplication life cycle
which is when the HttpApplication
object initializes (multiple times,
once for each instance of
HttpApplication). The only method
where this works correct is
HttpApplication Init().

To hook up a module via code you can
run code like the following instead of
the HttpModule definition in
web.config:

  public class Global : System.Web.HttpApplication
  {
     // some modules use explicit interface implementation
     // by declaring this static member as the IHttpModule interface
     // we work around that
     public static IHttpModule Module = new xrnsToashxMappingModule();
     public override void Init()
     {
         base.Init();
         Module.Init(this);
     }
  }

All you do is override the HttpApplication’s Init() method and
then access the static instance’s Init
method. Init() of the module hooks up
the event and off you go.

Via Rick Strahl’s blog

Leave a Comment