前言

本篇文章著重講一下在.Net中Host主機的構建過程,依舊延續之前文章的思路,著重講解其原始碼,如果有不知道有哪些用法的同學可以點選這裡,廢話不多說,咱們直接進入正題

Host構建過程

下圖是我自己整理的Host構建過程以及裡面包含的知識點我都以連結的形式放上來,大家可以看下圖,大概瞭解下過程(由於知識點過多,所以只能分上下兩張圖了):

圖中標識的相關知識點連線如下(ps:與編號對應):

以上就是筆者在原始碼閱讀階段,其總結的自我感覺重要的知識點在微軟文件中的對應位置。

原始碼解析

這部分筆者根據上圖中的四大塊分別進行原始碼解析,可能篇幅比較長,其主要是對原始碼增加了自己理解的註釋,所以讀者在閱讀的過程中,要多注意原始碼中的註釋(ps:展示出的程式碼不是全部程式碼,而只是重要程式碼哦,每個小節總結的點都是按照程式碼順序解釋)

初始化預設配置ConfigDefaultBuilder

  1. public static IHostBuilder ConfigureDefaults(this IHostBuilder builder, string[] args)
  2. {
  3. //設定程式執行路徑
  4. builder.UseContentRoot(Directory.GetCurrentDirectory());
  5. builder.ConfigureHostConfiguration(config =>
  6. {
  7. //新增獲取環境變數的字首
  8. config.AddEnvironmentVariables(prefix: "DOTNET_");
  9. //新增命令列引數
  10. if (args is { Length: > 0 })
  11. {
  12. config.AddCommandLine(args);
  13. }
  14. });
  15. builder.ConfigureAppConfiguration((hostingContext, config) =>
  16. {
  17. //宿主機環境資訊
  18. IHostEnvironment env = hostingContext.HostingEnvironment;
  19. //是否在檔案改變時重新載入,預設是True
  20. bool reloadOnChange = GetReloadConfigOnChangeValue(hostingContext);
  21. //預設新增的配置檔案(格外新增以環境變數為名稱的檔案)
  22. config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: reloadOnChange)
  23. .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: reloadOnChange);
  24. //如果是開發環境,並且應用程式的應用名稱不是空字串,則載入使用者機密,預設true(主要是為了不同開發人員的配置不同)
  25. if (env.IsDevelopment() && env.ApplicationName is { Length: > 0 })
  26. {
  27. var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
  28. if (appAssembly is not null)
  29. {
  30. config.AddUserSecrets(appAssembly, optional: true, reloadOnChange: reloadOnChange);
  31. }
  32. }
  33. //這裡再次執行是為了讓環境變數和命令列引數的配置優先順序提高(後加載的key/value獲取時優先順序最高)
  34. //新增其他環境變數
  35. config.AddEnvironmentVariables();
  36. //新增命令列引數
  37. if (args is { Length: > 0 })
  38. {
  39. config.AddCommandLine(args);
  40. }
  41. })
  42. .ConfigureLogging((hostingContext, logging) =>
  43. {
  44. //判斷作業系統
  45. bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
  46. if (isWindows)
  47. {
  48. //新增過濾規則,捕獲warning日誌
  49. logging.AddFilter<EventLogLoggerProvider>(level => level >= LogLevel.Warning);
  50. }
  51. //獲取Logging配置
  52. logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
  53. //新增輸出到控制檯
  54. logging.AddConsole();
  55. //新增將debug日誌輸出到控制檯
  56. logging.AddDebug();
  57. //新增寫入的事件源
  58. logging.AddEventSourceLogger();
  59. if (isWindows)
  60. {
  61. //新增事件日誌
  62. logging.AddEventLog();
  63. }
  64. //新增鏈路追蹤選項
  65. logging.Configure(options =>
  66. {
  67. options.ActivityTrackingOptions =
  68. ActivityTrackingOptions.SpanId |
  69. ActivityTrackingOptions.TraceId |
  70. ActivityTrackingOptions.ParentId;
  71. });
  72. })
  73. .UseDefaultServiceProvider((context, options) =>
  74. {
  75. bool isDevelopment = context.HostingEnvironment.IsDevelopment();
  76. //依賴注入相關校驗
  77. options.ValidateScopes = isDevelopment;
  78. options.ValidateOnBuild = isDevelopment;
  79. });
  80. return builder;
  81. }

原始碼總結:

  • 設定程式執行路徑以及獲取環境變數和載入命令列引數。
  • 根據環境變數載入appsettings.json,載入使用者機密資料(僅開發環境)。
  • 接著又載入環境變數和命令列引數(這裡為什麼又載入了一次呢?是因為這它們執行的順序是不一樣的,而後載入的會覆蓋前面載入的Key/Value,前面載入主要是確定當前執行的環境變數以及使用者自定義的命令列引數,後面是為確保通過key獲取value的時候能夠獲取到準確的值)。
  • 接下來就主要是配置預設Log,如果是開發環境,依賴注入相關的配置預設開啟(驗證scope是否被用於singleton,驗證是否在呼叫期間就建立所有服務至快取)。

初始化主機啟動配置ConfigureWebHostDefaults

  1. public GenericWebHostBuilder(IHostBuilder builder, WebHostBuilderOptions options)
  2. {
  3. _builder = builder;
  4. var configBuilder = new ConfigurationBuilder()
  5. .AddInMemoryCollection();
  6. //新增以ASPNETCORE_開頭的環境變數(ps:判斷當前環境是那個環境)
  7. if (!options.SuppressEnvironmentConfiguration)
  8. {
  9. configBuilder.AddEnvironmentVariables(prefix: "ASPNETCORE_");
  10. }
  11. //這裡主要載入環境變數
  12. _config = configBuilder.Build();
  13. _builder.ConfigureHostConfiguration(config =>
  14. {
  15. //將上面的配置載入進來
  16. config.AddConfiguration(_config);
  17. //通過配置和特性載入額外的Config(或者不載入配置),通過繼承IHostingStartup無侵入性載入。
  18. ExecuteHostingStartups();
  19. });
  20. //將上面Startup中Config的配置放到Build階段載入
  21. _builder.ConfigureAppConfiguration((context, configurationBuilder) =>
  22. {
  23. if (_hostingStartupWebHostBuilder != null)
  24. {
  25. var webhostContext = GetWebHostBuilderContext(context);
  26. _hostingStartupWebHostBuilder.ConfigureAppConfiguration(webhostContext, configurationBuilder);
  27. }
  28. });
  29. //增加註入的服務
  30. _builder.ConfigureServices((context, services) =>
  31. {
  32. var webhostContext = GetWebHostBuilderContext(context);
  33. var webHostOptions = (WebHostOptions)context.Properties[typeof(WebHostOptions)];
  34. //注入一些其他服務
  35. services.AddSingleton(webhostContext.HostingEnvironment);
  36. services.AddSingleton((AspNetCore.Hosting.IHostingEnvironment)webhostContext.HostingEnvironment);
  37. services.AddSingleton<IApplicationLifetime, GenericWebHostApplicationLifetime>();
  38. services.Configure<GenericWebHostServiceOptions>(options =>
  39. {
  40. options.WebHostOptions = webHostOptions;
  41. options.HostingStartupExceptions = _hostingStartupErrors;
  42. });
  43. services.TryAddSingleton(sp => new DiagnosticListener("Microsoft.AspNetCore"));
  44. services.TryAddSingleton<DiagnosticSource>(sp => sp.GetRequiredService<DiagnosticListener>());
  45. services.TryAddSingleton(sp => new ActivitySource("Microsoft.AspNetCore"));
  46. services.TryAddSingleton<IHttpContextFactory, DefaultHttpContextFactory>();
  47. services.TryAddScoped<IMiddlewareFactory, MiddlewareFactory>();
  48. services.TryAddSingleton<IApplicationBuilderFactory, ApplicationBuilderFactory>();
  49. _hostingStartupWebHostBuilder?.ConfigureServices(webhostContext, services);
  50. //可以通過配置的方式查詢程式集載入StartUp,但是預設只會載入最後一個StartUp
  51. if (!string.IsNullOrEmpty(webHostOptions.StartupAssembly))
  52. {
  53. try
  54. {
  55. var startupType = StartupLoader.FindStartupType(webHostOptions.StartupAssembly, webhostContext.HostingEnvironment.EnvironmentName);
  56. UseStartup(startupType, context, services);
  57. }
  58. catch (Exception ex) when (webHostOptions.CaptureStartupErrors)
  59. {
  60. var capture = ExceptionDispatchInfo.Capture(ex);
  61. services.Configure<GenericWebHostServiceOptions>(options =>
  62. {
  63. options.ConfigureApplication = app =>
  64. {
  65. capture.Throw();
  66. };
  67. });
  68. }
  69. }
  70. });
  71. }
  72. internal static void ConfigureWebDefaults(IWebHostBuilder builder)
  73. {
  74. //提供.netCore 靜態Web資產(ps:說實話這裡不知道有什麼用)
  75. builder.ConfigureAppConfiguration((ctx, cb) =>
  76. {
  77. if (ctx.HostingEnvironment.IsDevelopment())
  78. {
  79. StaticWebAssetsLoader.UseStaticWebAssets(ctx.HostingEnvironment, ctx.Configuration);
  80. }
  81. });
  82. //使用 Kestrel 配置反向代理
  83. builder.UseKestrel((builderContext, options) =>
  84. {
  85. options.Configure(builderContext.Configuration.GetSection("Kestrel"), reloadOnChange: true);
  86. })
  87. .ConfigureServices((hostingContext, services) =>
  88. {
  89. //配置啟動的Url
  90. services.PostConfigure<HostFilteringOptions>(options =>
  91. {
  92. if (options.AllowedHosts == null || options.AllowedHosts.Count == 0)
  93. {
  94. var hosts = hostingContext.Configuration["AllowedHosts"]?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
  95. options.AllowedHosts = (hosts?.Length > 0 ? hosts : new[] { "*" });
  96. }
  97. });
  98. services.AddSingleton<IOptionsChangeTokenSource<HostFilteringOptions>>(
  99. new ConfigurationChangeTokenSource<HostFilteringOptions>(hostingContext.Configuration));
  100. services.AddTransient<IStartupFilter, HostFilteringStartupFilter>();
  101. //用來獲取客戶端的IP地址
  102. if (string.Equals("true", hostingContext.Configuration["ForwardedHeaders_Enabled"], StringComparison.OrdinalIgnoreCase))
  103. {
  104. services.Configure<ForwardedHeadersOptions>(options =>
  105. {
  106. options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
  107. options.KnownNetworks.Clear();
  108. options.KnownProxies.Clear();
  109. });
  110. services.AddTransient<IStartupFilter, ForwardedHeadersStartupFilter>();
  111. }
  112. //新增路由配置
  113. services.AddRouting();
  114. })
  115. //預設使用IIS
  116. .UseIIS()
  117. //使用程序內的託管模式
  118. .UseIISIntegration();
  119. }

這部分內容可能會多點,原始碼總結:

  • 新增Memory快取,新增ASPNETCORE_開頭的環境變數。
  • 根據使用者的配置,來載入額外的StartUp中Config配置,但是它的引數是IWebHostBuilder,這部分可以參考微軟文件StartUp的部分。
  • 如果有存在這些配置的話,則統一放到Build階段載入。
  • 載入web主機需要的注入的服務,以及判斷是否需要通過程式集來載入StartUp,並且新增一個程式啟動時呼叫的服務(這裡主要是構建HttpContext執行管道)。
  • 引用Kestrel,繼承路由和IIS,並且預設使用程序內託管。
  • 載入使用者自定義的其他配置,例如預設的呼叫UseStartup方法。

根據指定配置開始初始化主機Build

  1. public class HostBuilder : IHostBuilder
  2. {
  3. private List<Action<IConfigurationBuilder>> _configureHostConfigActions = new List<Action<IConfigurationBuilder>>();
  4. private List<Action<HostBuilderContext, IConfigurationBuilder>> _configureAppConfigActions = new List<Action<HostBuilderContext, IConfigurationBuilder>>();
  5. private List<Action<HostBuilderContext, IServiceCollection>> _configureServicesActions = new List<Action<HostBuilderContext, IServiceCollection>>();
  6. private List<IConfigureContainerAdapter> _configureContainerActions = new List<IConfigureContainerAdapter>();
  7. private IServiceFactoryAdapter _serviceProviderFactory = new ServiceFactoryAdapter<IServiceCollection>(new DefaultServiceProviderFactory());
  8. private bool _hostBuilt;
  9. private IConfiguration _hostConfiguration;
  10. private IConfiguration _appConfiguration;
  11. private HostBuilderContext _hostBuilderContext;
  12. private HostingEnvironment _hostingEnvironment;
  13. private IServiceProvider _appServices;
  14. private PhysicalFileProvider _defaultProvider;
  15. public IDictionary<object, object> Properties { get; } = new Dictionary<object, object>();
  16. public IHostBuilder ConfigureHostConfiguration(Action<IConfigurationBuilder> configureDelegate)
  17. {
  18. _configureHostConfigActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate)));
  19. return this;
  20. }
  21. public IHostBuilder ConfigureAppConfiguration(Action<HostBuilderContext, IConfigurationBuilder> configureDelegate)
  22. {
  23. _configureAppConfigActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate)));
  24. return this;
  25. }
  26. public IHostBuilder ConfigureServices(Action<HostBuilderContext, IServiceCollection> configureDelegate)
  27. {
  28. _configureServicesActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate)));
  29. return this;
  30. }
  31. public IHostBuilder UseServiceProviderFactory<TContainerBuilder>(IServiceProviderFactory<TContainerBuilder> factory)
  32. {
  33. _serviceProviderFactory = new ServiceFactoryAdapter<TContainerBuilder>(factory ?? throw new ArgumentNullException(nameof(factory)));
  34. return this;
  35. }
  36. public IHostBuilder UseServiceProviderFactory<TContainerBuilder>(Func<HostBuilderContext, IServiceProviderFactory<TContainerBuilder>> factory)
  37. {
  38. _serviceProviderFactory = new ServiceFactoryAdapter<TContainerBuilder>(() => _hostBuilderContext, factory ?? throw new ArgumentNullException(nameof(factory)));
  39. return this;
  40. }
  41. public IHostBuilder ConfigureContainer<TContainerBuilder>(Action<HostBuilderContext, TContainerBuilder> configureDelegate)
  42. {
  43. _configureContainerActions.Add(new ConfigureContainerAdapter<TContainerBuilder>(configureDelegate
  44. ?? throw new ArgumentNullException(nameof(configureDelegate))));
  45. return this;
  46. }
  47. public IHost Build()
  48. {
  49. //只能執行一次這個方法
  50. if (_hostBuilt)
  51. {
  52. throw new InvalidOperationException(SR.BuildCalled);
  53. }
  54. _hostBuilt = true;
  55. using var diagnosticListener = new DiagnosticListener("Microsoft.Extensions.Hosting");
  56. const string hostBuildingEventName = "HostBuilding";
  57. const string hostBuiltEventName = "HostBuilt";
  58. if (diagnosticListener.IsEnabled() && diagnosticListener.IsEnabled(hostBuildingEventName))
  59. {
  60. Write(diagnosticListener, hostBuildingEventName, this);
  61. }
  62. //執行Host配置(應用程式執行路徑,載入_dotnet環境變數,獲取命令列引數,載入預配置)
  63. BuildHostConfiguration();
  64. //設定主機環境變數
  65. CreateHostingEnvironment();
  66. //構建HostBuilderContext例項
  67. CreateHostBuilderContext();
  68. //構建程式配置(載入appsetting.json,環境變數,命令列引數等)
  69. BuildAppConfiguration();
  70. //構造容器,注入服務
  71. CreateServiceProvider();
  72. var host = _appServices.GetRequiredService<IHost>();
  73. if (diagnosticListener.IsEnabled() && diagnosticListener.IsEnabled(hostBuiltEventName))
  74. {
  75. Write(diagnosticListener, hostBuiltEventName, host);
  76. }
  77. return host;
  78. }
  79. private static void Write<T>(
  80. DiagnosticSource diagnosticSource,
  81. string name,
  82. T value)
  83. {
  84. diagnosticSource.Write(name, value);
  85. }
  86. private void BuildHostConfiguration()
  87. {
  88. IConfigurationBuilder configBuilder = new ConfigurationBuilder()
  89. .AddInMemoryCollection();
  90. foreach (Action<IConfigurationBuilder> buildAction in _configureHostConfigActions)
  91. {
  92. buildAction(configBuilder);
  93. }
  94. //本質是執行ConfigureProvider中的Load方法,載入對應配置
  95. _hostConfiguration = configBuilder.Build();
  96. }
  97. private void CreateHostingEnvironment()
  98. {
  99. //設定環境變數
  100. _hostingEnvironment = new HostingEnvironment()
  101. {
  102. ApplicationName = _hostConfiguration[HostDefaults.ApplicationKey],
  103. EnvironmentName = _hostConfiguration[HostDefaults.EnvironmentKey] ?? Environments.Production,
  104. ContentRootPath = ResolveContentRootPath(_hostConfiguration[HostDefaults.ContentRootKey], AppContext.BaseDirectory),
  105. };
  106. if (string.IsNullOrEmpty(_hostingEnvironment.ApplicationName))
  107. {
  108. _hostingEnvironment.ApplicationName = Assembly.GetEntryAssembly()?.GetName().Name;
  109. }
  110. //程式執行路徑
  111. _hostingEnvironment.ContentRootFileProvider = _defaultProvider = new PhysicalFileProvider(_hostingEnvironment.ContentRootPath);
  112. }
  113. private void CreateHostBuilderContext()
  114. {
  115. _hostBuilderContext = new HostBuilderContext(Properties)
  116. {
  117. HostingEnvironment = _hostingEnvironment,
  118. Configuration = _hostConfiguration
  119. };
  120. }
  121. private void BuildAppConfiguration()
  122. {
  123. //對於已經載入過的配置不再重新載入
  124. IConfigurationBuilder configBuilder = new ConfigurationBuilder()
  125. .SetBasePath(_hostingEnvironment.ContentRootPath)
  126. .AddConfiguration(_hostConfiguration, shouldDisposeConfiguration: true);
  127. //注意這裡是AppConfig
  128. foreach (Action<HostBuilderContext, IConfigurationBuilder> buildAction in _configureAppConfigActions)
  129. {
  130. buildAction(_hostBuilderContext, configBuilder);
  131. }
  132. _appConfiguration = configBuilder.Build();
  133. //將新的配置賦值給config
  134. _hostBuilderContext.Configuration = _appConfiguration;
  135. }
  136. private void CreateServiceProvider()
  137. {
  138. var services = new ServiceCollection();
  139. services.AddSingleton<IHostingEnvironment>(_hostingEnvironment);
  140. services.AddSingleton<IHostEnvironment>(_hostingEnvironment);
  141. services.AddSingleton(_hostBuilderContext);
  142. services.AddSingleton(_ => _appConfiguration);
  143. services.AddSingleton<IApplicationLifetime>(s => (IApplicationLifetime)s.GetService<IHostApplicationLifetime>());
  144. services.AddSingleton<IHostApplicationLifetime, ApplicationLifetime>();
  145. services.AddSingleton<IHostLifetime, ConsoleLifetime>();
  146. services.AddSingleton<IHost>(_ =>
  147. {
  148. return new Internal.Host(_appServices,
  149. _hostingEnvironment,
  150. _defaultProvider,
  151. _appServices.GetRequiredService<IHostApplicationLifetime>(),
  152. _appServices.GetRequiredService<ILogger<Internal.Host>>(),
  153. _appServices.GetRequiredService<IHostLifetime>(),
  154. _appServices.GetRequiredService<IOptions<HostOptions>>());
  155. });
  156. services.AddOptions().Configure<HostOptions>(options => { options.Initialize(_hostConfiguration); });
  157. services.AddLogging();
  158. //主要載入額外注入的服務
  159. foreach (Action<HostBuilderContext, IServiceCollection> configureServicesAction in _configureServicesActions)
  160. {
  161. configureServicesAction(_hostBuilderContext, services);
  162. }
  163. //這裡返回object,主要是為了保留擴充套件,讓使用者自定義的依賴注入框架能夠執行。
  164. object containerBuilder = _serviceProviderFactory.CreateBuilder(services);
  165. foreach (IConfigureContainerAdapter containerAction in _configureContainerActions)
  166. {
  167. containerAction.ConfigureContainer(_hostBuilderContext, containerBuilder);
  168. }
  169. _appServices = _serviceProviderFactory.CreateServiceProvider(containerBuilder);
  170. if (_appServices == null)
  171. {
  172. throw new InvalidOperationException(SR.NullIServiceProvider);
  173. }
  174. //可能是想先把IConfiguration載入到記憶體中
  175. _ = _appServices.GetService<IConfiguration>();
  176. }
  177. }

在上面的兩個小單元可以看出,所有的構造是以委託的方式,最後都載入到HostBuilder內部的委託集合中,原始碼總結:

  • 載入環境變數和命令列引數。
  • 構建HostingEnvironment物件。
  • 構建HostBuilderContext物件,裡面包含配置和執行環境。
  • 載入appsettings.json,環境變數和命令列引數等。
  • 注入一些必須的服務,載入日誌配置,WebHost裡面注入的服務,載入StartUp裡面ConfigService裡面的服務,以及其他的一些注入的服務,構建容器(最後那裡獲取IConfiguration猜測可能是想先快取到根容器吧)。

執行主機Run

  1. public async Task StartAsync(CancellationToken cancellationToken = default)
  2. {
  3. _logger.Starting();
  4. using var combinedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _applicationLifetime.ApplicationStopping);
  5. CancellationToken combinedCancellationToken = combinedCancellationTokenSource.Token;
  6. //應用程式啟動和關閉事件
  7. await _hostLifetime.WaitForStartAsync(combinedCancellationToken).ConfigureAwait(false);
  8. combinedCancellationToken.ThrowIfCancellationRequested();
  9. _hostedServices = Services.GetService<IEnumerable<IHostedService>>();
  10. //主要是執行一些後臺任務,可以重寫啟動和關閉時要做的操作
  11. foreach (IHostedService hostedService in _hostedServices)
  12. {
  13. //立即執行的任務,例如構建管道就是在這裡
  14. await hostedService.StartAsync(combinedCancellationToken).ConfigureAwait(false);
  15. //執行一些後臺任務
  16. if (hostedService is BackgroundService backgroundService)
  17. {
  18. _ = TryExecuteBackgroundServiceAsync(backgroundService);
  19. }
  20. }
  21. //通知應用程式啟動成功
  22. _applicationLifetime.NotifyStarted();
  23. //程式啟動
  24. _logger.Started();
  25. }

原始碼總結:

  • 監聽程式的啟動關閉事件。
  • 開始執行Hosted服務或者載入後臺執行的任務。
  • 通過TaskCompletionSource來持續監聽Token,hold住程序。

總結

通過模板來構建的.Net泛型主機,其實已經可以滿足大部分的要求,並且微軟保留大量擴充套件讓使用者來自定義,當然你也可以構建其他不同的主機型別(如:Web主機或者控制檯程式啟動項配置),想了解的可以點選這裡

以上就是筆者通過閱讀原始碼來分析的程式執行流程,因為篇幅問題沒有把所有程式碼都放出來,實在是太多了,所以只放了部分程式碼,主要是想給閱讀原始碼的同學在閱讀的時候找到思路,可能會有一點錯誤,還請評論指正。