標籤:
前言
asp.net core 出來一個來月了,自己在工作課餘時間準備讀一下它的原始碼,會把一系列的理解和想法記錄下來,同時更希望能夠得到園子裡同行的指點,共同進步,這裡只是我對原始碼的理解,有錯誤地方,望大家指正,這將會是一系列的文章。
入口
建立一個asp.net core項目後可以看到一個Program.cs和一個Startup.cs,今天主要研究一下Program.cs到底都做了些什麼,
public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); }View Code
這裡main方法是應用程式的入口不用多說,可以看到在入口處建立了一個WebHostBuilder的執行個體對象,然後對他進行了一系列的配置,最後執行Build方法返回一個IWebHost對象的執行個體,最後執行他的Run,方法,至此,應用程式啟動起來了,那麼這一系列的配置到底做了什麼,我們需要看WebHost這個類,我們去github上面把原始碼下載下來慢慢看。連結是aspnet/hosting,下載下來後可以直接用VS2015 update3 開啟。首先我們要先來看WebHostBuilder這個類
WebHostBuilder
這個類的執行個體是為了建立WebHost的類執行個體而準備的,我們看一下他的構造方法:
public WebHostBuilder() { _hostingEnvironment = new HostingEnvironment(); _configureServicesDelegates = new List<Action<IServiceCollection>>(); _configureLoggingDelegates = new List<Action<ILoggerFactory>>(); _config = new ConfigurationBuilder() .AddEnvironmentVariables(prefix: "ASPNETCORE_") .Build(); if (string.IsNullOrEmpty(GetSetting(WebHostDefaults.EnvironmentKey))) { // Try adding legacy environment keys, never remove these. UseSetting(WebHostDefaults.EnvironmentKey, Environment.GetEnvironmentVariable("Hosting:Environment") ?? Environment.GetEnvironmentVariable("ASPNET_ENV")); } if (string.IsNullOrEmpty(GetSetting(WebHostDefaults.ServerUrlsKey))) { // Try adding legacy url key, never remove this. UseSetting(WebHostDefaults.ServerUrlsKey, Environment.GetEnvironmentVariable("ASPNETCORE_SERVER.URLS")); } }View Code
這個方法裡面初始化一些基本的變數,_hostingEnvironment(host的環境配置,包括環境名字,應用程式的名字,webroot的路徑,ContentRoot的路徑),_configureServicesDelegates(從名字上來看是服務作業的委託集合),_configureLoggingDelegates(從名字上看是日誌操作的委託集合),_config(配置建立器的一個執行個體),然後會向_config中寫入兩個配置(“environment”和“urls”)。
然後調用擴充方法UseKestrel(),我們來看代碼:
public static IWebHostBuilder UseKestrel(this IWebHostBuilder hostBuilder) { return hostBuilder.ConfigureServices((Action<IServiceCollection>) (services => { ServiceCollectionServiceExtensions.AddTransient<IConfigureOptions<KestrelServerOptions>, KestrelServerOptionsSetup>(services); ServiceCollectionServiceExtensions.AddSingleton<IServer, KestrelServer>(services); })); }View Code
這個方法是調用WebHostBuilder的ConfigureServices方法增加了Kestrel對host的一些委託處理方法,這些委託方法主要包括將Kestrel以及它的一些配置選項加入到應用程式的服務處理集合。
然後調用UseContentRoot(Directory.GetCurrentDirectory())方法,我們來看代碼:
public static IWebHostBuilder UseContentRoot(this IWebHostBuilder hostBuilder, string contentRoot) { if (contentRoot == null) throw new ArgumentNullException("contentRoot"); return hostBuilder.UseSetting(WebHostDefaults.ContentRootKey, contentRoot); }View Code
這個擴充方法依舊是調用UseSeeting()方法給_config配置中添加配置項“contentRoot”(應用程式的內容目錄,詳見連結),值為當前的目錄.
然後調用UseIISIntegration()這個擴充方法,我們來看代碼:
public static IWebHostBuilder UseIISIntegration(this IWebHostBuilder app) { if (app == null) throw new ArgumentNullException("app"); string str1 = app.GetSetting(WebHostBuilderIISExtensions.ServerPort) ?? Environment.GetEnvironmentVariable(string.Format("ASPNETCORE_{0}", (object) WebHostBuilderIISExtensions.ServerPort)); string str2 = app.GetSetting(WebHostBuilderIISExtensions.ServerPath) ?? Environment.GetEnvironmentVariable(string.Format("ASPNETCORE_{0}", (object) WebHostBuilderIISExtensions.ServerPath)); string pairingToken = app.GetSetting(WebHostBuilderIISExtensions.PairingToken) ?? Environment.GetEnvironmentVariable(string.Format("ASPNETCORE_{0}", (object) WebHostBuilderIISExtensions.PairingToken)); if (!string.IsNullOrEmpty(str1) && !string.IsNullOrEmpty(str2) && !string.IsNullOrEmpty(pairingToken)) { string str3 = "http://localhost:" + str1 + str2; app.UseSetting(WebHostDefaults.ServerUrlsKey, str3); HostingAbstractionsWebHostBuilderExtensions.CaptureStartupErrors(app, true); app.ConfigureServices((Action<IServiceCollection>) (services => { ServiceCollectionServiceExtensions.AddSingleton<IStartupFilter>(services, (IStartupFilter) new IISSetupFilter(pairingToken)); OptionsServiceCollectionExtensions.Configure<ForwardedHeadersOptions>(services, (Action<ForwardedHeadersOptions>) (options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; bool flag = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID")); options.RequireHeaderSymmetry = !flag; })); })); } return app; }View Code
這裡主要是對IIS的一些配置,我的理解是IIS會把它監聽的到的請求轉交給Kestrel來做處理,所以真正的監聽還是在IIS,當然這一步也可以直接省去,直接有Kestrel來監聽連接埠的請求。注釋掉這個方法的調用,啟動應用程式直接存取 localhost:5000一樣可以(你可以試一試的)。
接著是 UseStartup<Startup>() 這個方法,這個方法和Startup這個類,我會在下一篇做單獨的講解,主要是設定Aspnet core的處理模組(我們這裡就是MVC的處理)
最後是Builder()方法:
public IWebHost Build() { // Warn about deprecated environment variables if (Environment.GetEnvironmentVariable("Hosting:Environment") != null) { Console.WriteLine("The environment variable ‘Hosting:Environment‘ is obsolete and has been replaced with ‘ASPNETCORE_ENVIRONMENT‘"); } if (Environment.GetEnvironmentVariable("ASPNET_ENV") != null) { Console.WriteLine("The environment variable ‘ASPNET_ENV‘ is obsolete and has been replaced with ‘ASPNETCORE_ENVIRONMENT‘"); } if (Environment.GetEnvironmentVariable("ASPNETCORE_SERVER.URLS") != null) { Console.WriteLine("The environment variable ‘ASPNETCORE_SERVER.URLS‘ is obsolete and has been replaced with ‘ASPNETCORE_URLS‘"); } var hostingServices = BuildHostingServices(); var hostingContainer = hostingServices.BuildServiceProvider(); var host = new WebHost(hostingServices, hostingContainer, _options, _config); host.Initialize(); return host; }View Code
這個方法根據之前註冊的一系列的服務(監聽服務,Log Service等等)和配置,產生一個應用程式的最終宿主host,並且初始化他(裡面的調用和建立方法原始碼都很清晰)。
然後調用host.run()方法,啟動服務,run方法的具體調用會單獨一個章節來分析。
總結
這篇文章只是對建立一個host對象做了一些系統的描述,裡面的具體實現真的很多很多,有一些我還沒有看到,感覺每一個方法都有很多的東西,我會慢慢完善,有理解錯誤的地方,希望大家指出來。願.NET的生態圈越來越好,大家一起努力。給大家推薦一個網址連結
裡面有關於aspnet的線上討論。
如果你感覺對你有協助,麻煩推薦一下。
asp.net core 源碼系列(一)