Adding Modules Dynamically to ASP.NET

As you may already know, ASP.NET 4.0 brought along with it a new mechanism to execute methods before the application start event (the Application_Start method): the PreApplicationStartMethodAttribute. This attribute, when applied to an assembly, indicates a method which is to be run before the application starts. If your web application references any assembly which has this attribute, it will run the method it declares, throwing an exception it if is not found.

Of course, you may like or dislike this new behavior, but it is here, and there’s no way to make it go away, so let’s try to make some use out of it.

As it happens, ASP.NET MVC 3 introduces the Microsoft.Web.Infrastructure assembly (normally placed in C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies) which has a static class called Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility with a single public method:  RegisterModule. This method can be used to add a module (IHttpModule) to the application dynamically, that is, without registering it on the Web.config file.

Here’s an example:

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Text;
   5: using System.Web;
   6: using Microsoft.Web.Infrastructure.DynamicModuleHelper;
   7:  
   8: [assembly: PreApplicationStartMethod(typeof(AutoModuleLibrary.AutoModule), "Install")]
   9:  
  10: namespace AutoModuleLibrary
  11: {
  12:     public class AutoModule: IHttpModule
  13:     {
  14:         public static void Install()
  15:         {
  16:             DynamicModuleUtility.RegisterModule(typeof(AutoModule));
  17:         }
  18:  
  19:         public void Dispose()
  20:         {
  21:         }
  22:  
  23:         public void Init(HttpApplication context)
  24:         {
  25:         }
  26:     }
  27: }

If you are concerned about the security implications, you must know that the method declared in the PreApplicationStartMethodAttribute attribute has no access to the current application context: the HttpContext.Current property is null; however, the static properties on HttpRuntime and AppDomain.CurrentDomain are not.

Have a try!

Bookmark and Share

                             

No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website