Sunday, 16 October 2011

Dynamic HttpModule registration in .NET Framework 4.0

This article could be useful for the scenario that you are developing HttpModule handling related functionality for a web application and you do not have the right to or not intend to modify the Global.asax file to register your HttpModule handler.

So here we go. Step 1, before register a HttpModule handler dynamically the first thing is to create the handler. See code below:

public class MyDynamicModule : IHttpModule
{
    void IHttpModule.Dispose()
    {
    }
 
    void IHttpModule.Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
        context.EndRequest += new EventHandler(context_EndRequest);
    }
    //... more code ignored
}

Step 2, to register this HttpModule handler, we need the reference to Microsoft.Web.Infrastructure assemble and use the contained method DynamicModuleUtility.RegisterModule. See sample code below:

DynamicModuleUtility.RegisterModule(typeof(MyDynamicModule));

But where we call this line of code? As you know HttpModule registration has to be done before the instance of HttpAppliction start. To achieve that we need the newly introduced attribute class System.Web.PreApplicationStartMethodAttribute in .NET framework 4.0. Note this attribute is assembly level attribute. See the code below, as step 3 of our example, of how to use the attribute:

[assembly: PreApplicationStartMethod(typeof(DynamicHttpModule), "RegisterMyModule")]

The code above basically says I want the web application to do something in its pre-start event, which is, to execute the static method DynamicHttpModule.RegisterMyModule, see below the code of the DynamicHttpModule class:

public static class DynamicHttpModule
{
    public static void RegisterMyModule()
    {
        DynamicModuleUtility.RegisterModule(typeof(MyDynamicModule)); //code from step 2
    }
}

And that is it.

No comments: