Friday, February 6, 2009

Inject application-specific code into ASP.NET module

We often write ASP.NET modules to customize ASP.NET processing pipeline - extend security, etc.

   1: public class ExampleModule : IHttpModule
   2:  {
   3:      #region IHttpModule Members
   4:  
   5:      public void Dispose() { }
   6:  
   7:      public void Init( HttpApplication context )
   8:      {
   9:          context.BeginRequest += new EventHandler( context_BeginRequest );
  10:      }
  11:  
  12:      void context_BeginRequest( object sender, EventArgs e )
  13:      {
  14:          // extend the processing pipeline by providing
  15:          // custom code for particular events, in this case
  16:          // the BeginRequest event
  17:      }
  18: }

However, as modules are static, in a sense that a module is active or inactive in processing pipeline, applications which "host" modules are dynamic, in a sense that different applications work under different conditions.


The issue we've faced recently was to inject a custom, application specific code into module:



   1: void context_BeginRequest( object sender, EventArgs e )
   2: {
   3:     // how to call an application-defined code
   4:     // but do it so that the module is not
   5:     // rewritten everytime application changes
   6:     
   7:     // ?
   8: }

The solution we've came up with was rather simple: we've used a custom provider to provide application-specific code.



   1: <system.web>
   2:     <specificProvider defaultProvider="ApplicationSpecificProvider">
   3:         <providers>
   4:             <add name="ApplicationSpecificProvider" type="Namespace.ApplicationSpecificProvider" />
   5:         </providers>
   6:     </specificProvider>

This way we can configure different providers on the application level but still be able to write generic module code:



   1: void context_BeginRequest( object sender, EventArgs e )
   2: {
   3:     HttpApplication app = (HttpApplication)sender;
   4:  
   5:     SpecificProvider.DoSpecificOperation( app );
   6: }

No comments: