文章內容
從上章文章都知道,asp.net是運行在HttpRuntime裡的,但是從CLR如何進入HttpRuntime的,可能大家都不太清晰。本章節就是通過深入分析.Net4的源碼來展示其中的重要步驟。請先看下圖:

首先,CLR在初始化加載的時候,會加載一個非常重要的類AppManagerAppDomainFactory,這個類是做什麼用的呢?首先這個類繼承了IAppManagerAppDomainFactory接口,而這個接口是是有個可供COM調用的Create方法,代碼如下:
[ComImport, Guid("02998279-7175-4d59-aa5a-fb8e44d4ca9d"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
public interface IAppManagerAppDomainFactory {
#if !FEATURE_PAL // FEATURE_PAL does not enable COM
[return: MarshalAs(UnmanagedType.Interface)]
#else // !FEATURE_PAL
Object Create(String appId, String appPath);
#endif // !FEATURE_PAL
Object Create([In, MarshalAs(UnmanagedType.BStr)] String appId,
[In, MarshalAs(UnmanagedType.BStr)] String appPath);
void Stop();
}
我們來細看一下這個AppManagerAppDomainFactory是如何實現這個接口的,首先該類在默認的構造函數裡,獲取了一個ApplicationManager的實例用於在Create方法裡使用。代碼如下:
[SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
public AppManagerAppDomainFactory() {
_appManager = ApplicationManager.GetApplicationManager();
_appManager.Open();
}
回到實現接口的Create方法,我們來看最重要的3行代碼:
ISAPIApplicationHost appHost = new ISAPIApplicationHost(appId, appPath, false /*validatePhysicalPath*/);
ISAPIRuntime isapiRuntime = (ISAPIRuntime)_appManager.CreateObjectInternal(appId, typeof(ISAPIRuntime), appHost,
false /*failIfExists*/, null /*hostingParameters*/);
isapiRuntime.StartProcessing();