MVC Series (6) Dynamic registration HttpModule

Source: Internet
Author: User
Tags assert config http request static class

Through the previous chapters, we know that HttpApplication initializes all of the httpmodules registered in the configuration file, so there is a question, can you initialize the dynamic load HttpModule before initialization, instead of just reading from web.config?

The answer is yes, asp.net MVC3 when the release provided a Microsoft.Web.Infrastructure.dll file, this file is to provide dynamic registration HttpModule function, then how it is registered? We first go to the source code of the MVC3 to see the DLL.

Note: The DLL location is under the C:\Program Files\Microsoft Asp.net\asp.net Web Pages\v1.0\assemblies\

We found a static class dynamicmoduleutility, and there was a registermodule method that caught my attention:

Call from Preappstart to dynamically register a 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);   
    }   

By code and annotation we can see that this method is to let us dynamically register IHttpModule, and because. Net4.5 already has helper class support, so it can be used directly, other versions use Legacymoduleregistrar.registermodule to dynamically register IHttpModule. And this method is divided into IIS6 and IIS7 integration or Classic mode, the code is generally consistent, we will only analyze the IIS6 version of the code:

private static void Addmoduletoclassicpipeline (Type moduletype) {//This works by essentially adding a new entry T o the  

The comment in the

Above code is very important, as we can see from the comment that the method starts with the Runtimeconfig.getappconfig (). HttpModules Gets the HttpModules collection, and then adds the new httpmodule that needs to be registered in the collection, which means that HttpApplication initializes all The HttpModule must be added to this collection before the HttpModule is to be registered, which is the cycle? Before HttpApplication was hostingenvironment, was it possible to register here? We went to the class to look at the relevant code, and in the Initialize method suddenly found a seemingly familiar code buildmanager.callprestartinitmethods (), the code is as follows:

Call AppInitialize, unless the flag says does not be 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 '-A/C them with the-a-HTTP request   
        Httprunt Ime. Initializationexception = e;   
      
        if ((Hostingflags & Hostingenvironmentflags.throwhostinginiterrors)!= 0) {   
            throw;  
        }  
    }  
}

By going to the BuildManager class to see the details of the method, we finally found the following method:

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 th   
            At 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 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; }

This column more highlights: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/aspx/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.