In part 1 of this series, I talked about building the UnityHttpModule. Now that we have this HttpModule written, we need to register it with the ASP.NET pipeline to service requests.
Registering the UnityHttpModule
Traditionally, in order to register an HttpModule
with the runtime you had to make a change to the web.config file. This was potentially prone to errors if it was placed incorrectly or you put it into the configuration section for IIS 7.0+ and not in the IIS 6.0 and earlier section.
Fortunately, Microsoft added support for just this scenario in the form of assembly 'pre-start' methods with the Microsoft.Web.Infrastructure
assembly.
Step 1 - Create a PreApplicationStart class
Create a new class as follows:
public class PreApplicationStart { private static bool _isStarting; public static void PreStart() { if ( !_isStarting ) { _isStarting = true; DynamicModuleUtility.RegisterModule( typeof( UnityHttpModule ) ); } } }
This simple class defines a static method that will get run when the application is first starting up. It uses the Microsoft.Infrastructure.DynamicModuleUtility
assembly to dynamically register an IHttpModule
. Presto! Adding a DLL to a project can now automatically register itself when the application is starting up... no more copy-pasta with web.config!
Step 2 - Invoking PreStart()
when the application starts
The only other step required is to tell the runtime to invoke the PreStart()
method when the application is starting. To do that, simply add the following to the AssemblyInfo.cs file in your project:
using System.Web; [assembly: PreApplicationStartMethod( typeof(Unity.WebForms.PreApplicationStart), "PreStart" )]
That's it!
Recap
Registering HttpModules (or HttpHandlers for that matter) is now really easy if you use the 'pre-start' methods from the Microsoft.Web.Infrastructure
in your Assembly; no more mucking with web.config!
No comments:
Post a Comment