動态注冊HttpModule使我們使用自定義的HttpModel時候不在需在配置檔案裡配置HttpModel,避免過多的配置出錯情況。讓我們來看看如何實作動态注冊HttpModule.
First,我們實作自定義的HttpModel
public class CustomModule : IHttpModule
{
public void Dispose()
{
// nothing to do here
}
public void Init(HttpApplication context)
{
context.BeginRequest += (sender, e) => ProcessCookie((HttpApplication)sender);
}
}
}
Second,建立一個靜态類,并命名為PreApplicationStartCode,并增加一個靜态方法PreStart()
public class PreApplicationStartCode
{
private static bool _isStarting;
public static void PreStart()
{
if ( ! _isStarting)
{
_isStarting = true ;
// 注意這裡的動态注冊,此靜态方法在Microsoft.Web.Infrastructure.DynamicModuleHelper
DynamicModuleUtility.RegisterModule( typeof (CustomModule));
}
}
}
Note.這裡的類名官方裡面建議用PreApplicationStartCode,我沒測試過,大家可以測試下用其他類名
Three,在Properties/AssemblyInfo.cs裡面注冊
[assembly: PreApplicationStartMethod( typeof (MyTest.PreApplicationStartCode), " PreStart " )]
通過這三步,你的HttpModule就不在需要為每個應用程式去配置了,這種方式比較适合開發元件DLL的時候,需要注冊HttpModule的情況,微軟的Asp.net MVC3裡都是使用的動态HttpModule,有興趣可以去看源碼。