前一篇提到WebHost.CreateDefaultBuilder(args)方法创建了WebHostBuilder实例,WebHostBuilder实例有三个主要功能 1、构建了IConfiguration实例和基础环境配置,2、构建了IServiceCollection服务,也就是依赖注入的容器,3、创建了webhost实例,这个webhost就是我们的接收请求的第一个管道,其中暴露出来的主要方法Build,请看源代码:
1 public IWebHost Build() 2 { 3 if (!_webHostBuilt) 4 { 5 _webHostBuilt = true; 6 AggregateException hostingStartupErrors; 7 IServiceCollection serviceCollection = BuildCommonServices(out hostingStartupErrors); 8 IServiceCollection serviceCollection2 = serviceCollection.Clone(); 9 IServiceProvider hostingServiceProvider = _003CBuild_003Eg__GetProviderFromFactory_007C13_0(serviceCollection); 10 if (!_options.SuppressStatusMessages) 11 { 12 if (Environment.GetEnvironmentVariable("Hosting:Environment") != null) 13 { 14 Console.WriteLine("The environment variable 'Hosting:Environment' is obsolete and has been replaced with 'ASPNETCORE_ENVIRONMENT'"); 15 } 16 if (Environment.GetEnvironmentVariable("ASPNET_ENV") != null) 17 { 18 Console.WriteLine("The environment variable 'ASPNET_ENV' is obsolete and has been replaced with 'ASPNETCORE_ENVIRONMENT'"); 19 } 20 if (Environment.GetEnvironmentVariable("ASPNETCORE_SERVER.URLS") != null) 21 { 22 Console.WriteLine("The environment variable 'ASPNETCORE_SERVER.URLS' is obsolete and has been replaced with 'ASPNETCORE_URLS'"); 23 } 24 } 25 AddApplicationServices(serviceCollection2, hostingServiceProvider); 26 WebHost webHost = new WebHost(serviceCollection2, hostingServiceProvider, _options, _config, hostingStartupErrors); 27 try 28 { 29 webHost.Initialize(); 30 ILogger<WebHost> requiredService = webHost.Services.GetRequiredService<ILogger<WebHost>>(); 31 foreach (IGrouping<string, string> item in from g in _options.GetFinalHostingStartupAssemblies().GroupBy((string a) => a, StringComparer.OrdinalIgnoreCase) 32 where g.Count() > 1 33 select g) 34 { 35 requiredService.LogWarning($"The assembly {item} was specified multiple times. Hosting startup assemblies should only be specified once."); 36 } 37 return webHost; 38 } 39 catch 40 { 41 webHost.Dispose(); 42 throw; 43 } 44 } 45 throw new InvalidOperationException(Resources.WebHostBuilder_SingleInstance); 46 }