MVC之前的那點事兒系列(6):動態註冊HttpModule

來源:互聯網
上載者:User

標籤:c   style   class   blog   code   java   

文章內容

通過前面的章節,我們知道HttpApplication在初始化的時候會初始化所有設定檔裡註冊的HttpModules,那麼有一個疑問,能否初始化之前動態載入HttpModule,而不是只從Web.config裡讀取?

答案是肯定的, ASP.NET MVC3發布的時候提供了一個Microsoft.Web.Infrastructure.dll檔案,這個檔案就是提供了動態註冊HttpModule的功能,那麼它是如何以註冊的呢?我們先去MVC3的源碼看看該DLL的原始碼。

註:該DLL位置在C:\Program Files\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies\下

我們發現了一個靜態類DynamicModuleUtility,裡面有個RegisterModule方法引起了我的注意:

// Call from PreAppStart to dynamically register an IHttpModule, just as if you had added it to the// <modules> section in Web.config. [SecuritySafeCritical] public static void RegisterModule(Type moduleType) {    if (DynamicModuleReflectionUtil.Fx45RegisterModuleDelegate != null) {         // The Fx45 helper exists, so just call it directly.        DynamicModuleReflectionUtil.Fx45RegisterModuleDelegate(moduleType);    }    else {         // Use private reflection to perform the hookup.        LegacyModuleRegistrar.RegisterModule(moduleType);     } }

通過代碼和注釋我們可以看到,這個方法就是讓我們動態註冊IHttpModule的,而且由於.Net4.5已經有helper類支援了,所以直接就可以用,其它版本使用LegacyModuleRegistrar.RegisterModule來動態註冊IHttpModule 的。而這個方法裡又分IIS6和IIS7整合或傳統模式之分,代碼大體上是一致的,我們這裡就只分析IIS6版本的代碼:

private static void AddModuleToClassicPipeline(Type moduleType) {    // This works by essentially adding a new entry to the <httpModules> section defined     // in ~/Web.config. Need to set the collection to read+write while we do this.     // httpModulesSection = RuntimeConfig.GetAppConfig().HttpModules;     // httpModulesSection.Modules.bReadOnly = false;    // httpModulesSection.Modules.Add(new HttpModuleAction(...));    // httpModulesSection.Modules.bReadOnly = true;     HttpModulesSection httpModulesSection = null;    try {         object appConfig = _reflectionUtil.GetAppConfig();         httpModulesSection = _reflectionUtil.GetHttpModulesFromAppConfig(appConfig);        _reflectionUtil.SetConfigurationElementCollectionReadOnlyBit(httpModulesSection.Modules, false /* value */);         DynamicModuleRegistryEntry newEntry = CreateDynamicModuleRegistryEntry(moduleType);        httpModulesSection.Modules.Add(new HttpModuleAction(newEntry.Name, newEntry.Type));    }     finally {        if (httpModulesSection != null) {             _reflectionUtil.SetConfigurationElementCollectionReadOnlyBit(httpModulesSection.Modules, true /* value */);         }    } }

上面代碼的注釋非常重要,通過注釋我們可以看到,該方法先從RuntimeConfig.GetAppConfig().HttpModules擷取HttpModules集合,然後在集合裡添加需要註冊的新HttpModule,那就是說HttpApplication在初始化所有HttpModule之前必須將需要註冊的HttpModule添加到這個集合裡,那是在哪個周期呢?HttpApplication之前是HostingEnvironment,那是不是在這裡可以註冊呢?我們去該類查看一下相關的代碼,在Initialize方法裡突然發現一個貌似很熟悉的代碼BuildManager.CallPreStartInitMethods(),代碼如下:

// call AppInitialize, unless the flag says not to do it (e.g. CBM scenario).// Also, don‘t call it if HostingInit failed (VSWhidbey 210495) if(!HttpRuntime.HostingInitFailed) {     try {        BuildManager.CallPreStartInitMethods();         if ((hostingFlags & HostingEnvironmentFlags.DontCallAppInitialize) == 0) {            BuildManager.CallAppInitializeMethod();        }    }     catch (Exception e) {        // could throw compilation errors in ‘code‘ - report them with first http request         HttpRuntime.InitializationException = e;         if ((hostingFlags & HostingEnvironmentFlags.ThrowHostingInitErrors) != 0) {             throw;        }    }}

通過去BuildManager類去查看該方法的詳情,最終發現了如下這個方法:

internal static ICollection<MethodInfo> GetPreStartInitMethodsFromAssemblyCollection(IEnumerable<Assembly> assemblies) {    List<MethodInfo> methods = new List<MethodInfo>();     foreach (Assembly assembly in assemblies) {        PreApplicationStartMethodAttribute[] attributes = null;        try {            attributes = (PreApplicationStartMethodAttribute[])assembly.GetCustomAttributes(typeof(PreApplicationStartMethodAttribute), inherit: true);         }        catch {             // GetCustomAttributes invokes the constructors of the attributes, so it is possible that they might throw unexpected exceptions.             // (Dev10 bug 831981)        }         if (attributes != null && attributes.Length != 0) {            Debug.Assert(attributes.Length == 1);            PreApplicationStartMethodAttribute attribute = attributes[0];             Debug.Assert(attribute != null);             MethodInfo method = null;             // Ensure the Type on the attribute is in the same assembly as the attribute itself            if (attribute.Type != null && !String.IsNullOrEmpty(attribute.MethodName) && attribute.Type.Assembly == assembly) {                 method = FindPreStartInitMethod(attribute.Type, attribute.MethodName);            }            if (method != null) {                 methods.Add(method);            }             else {                 throw new HttpException(SR.GetString(SR.Invalid_PreApplicationStartMethodAttribute_value,                    assembly.FullName,                     (attribute.Type != null ? attribute.Type.FullName : String.Empty),                    attribute.MethodName));            }        }     }    return methods; } 

發現了該方法會尋找應用程式下所有的程式集,判斷如果程式集標記為PreApplicationStartMethodAttribute特性,就會執行這個特性裡指定的方法(靜態方法),再檢查該類的代碼:

    [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]     public sealed class PreApplicationStartMethodAttribute : Attribute {         private readonly Type _type;        private readonly string _methodName;        public PreApplicationStartMethodAttribute(Type type, string methodName) {             _type = type;            _methodName = methodName;         }         public Type Type {   get { return _type; }   }         public string MethodName {  get {  return _methodName; }   }    }

這時候,心裡應該有數了吧,我們可以在這裡指定一個靜態方法名稱,然後在該方法去通過如下代碼去註冊一個自訂的HttpModule(注意我們只能使用一次):

DynamicModuleUtility.RegisterModule(typeof(CustomModule));

我們來做個實驗試試我們分析的結果是不是正確,首先建立一個自訂HttpModule,代碼如下:

public class CustomModule : IHttpModule{    public void Init(HttpApplication context)    {        context.BeginRequest += new EventHandler(context_BeginRequest);                }    void context_BeginRequest(object sender, EventArgs e)    {        HttpApplication ap = sender as HttpApplication;        if (ap != null)        {            ap.Response.Write("湯姆大叔測試PreApplicationStartMethod通過!<br/>");        }    }    public void Dispose()    {        //nothing to do here    }}

然後在建立一個用於註冊這個HttpModule的類並且帶有靜態方法:

public class PreApplicationStartCode{    private static bool hasLoaded;    public static void PreStart()    {        if (!hasLoaded)        {            hasLoaded = true;            //注意這裡的動態註冊,此靜態方法在Microsoft.Web.Infrastructure.DynamicModuleHelper            DynamicModuleUtility.RegisterModule(typeof(CustomModule));        }    }}

接著要安裝要求對該程式添加一個特性,代碼如下:

[assembly: PreApplicationStartMethod(typeof(WebApplication1.Test.PreApplicationStartCode), "PreStart")]

最後,編譯運行,會發現所有的頁面頂部都會出現我們指定的文字(湯姆大叔測試PreApplicationStartMethod通過!),如下:

這就證實了我們的分析結果是正確的,怎麼樣,這個功能不錯吧,不需要每次都在web.config裡定義你的HttpModule咯,而且我們以後封裝自己的類庫就方便多了,不需要在網站程式集裡指定代碼去啟動自己封裝好的單獨類庫了,因為我們可以在自己的類庫裡直接使用這種方式實現自動註冊的功能。下個章節,我們將介紹一個利用此功能開發的超強類庫。

註:同一個程式集只能使用一次這個特性來調用一個靜態方法。

同步與推薦

本文已同步至目錄索引:MVC之前的那點事兒系列

MVC之前的那點事兒系列文章,包括了原創,翻譯,轉載等各類型的文章,如果對你有用,請推薦支援一把,給大叔寫作的動力。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.