WebHost : IWebHost 2 { IServiceCollection _applicationServiceCollection;IStartup _startup;IServiceProvider _hostingServiceProvider;ApplicationLifetime _applicationLifetime; WebHostOptions _options; IConfiguration _config; IServiceProvider _applicationServices; RequestDelegate _application; 13 private IServer Server { get; set; } //服务器字段,包含了处理的请求的信息 Initialize() { 17 if (_application == null) 18 { 19 _application = BuildApplication(); 20 } 21 } EnsureApplicationServices() { 24 if (_applicationServices == null) 25 { 26 EnsureStartup(); 27 _applicationServices = _startup.ConfigureServices(_applicationServiceCollection); 28 } 29 } EnsureStartup() { 32 _startup = _hostingServiceProvider.GetRequiredService<IStartup>(); 33 } RequestDelegate BuildApplication() 37 { { 40 EnsureApplicationServices(); 41 EnsureServer(); builderFactory = _applicationServices.GetRequiredService<IApplicationBuilderFactory>(); 44 var builder = builderFactory.CreateBuilder(Server.Features); 45 builder.ApplicationServices = _applicationServices; startupFilters = _applicationServices.GetService<IEnumerable<IStartupFilter>>(); 48 Action<IApplicationBuilder> configure = _startup.Configure; 49 foreach (var filter in startupFilters.Reverse()) 50 { } 53 54 configure(builder); builder.Build();//Use方法最终都会ApplicationBuilder.Use()方法,以Fun<RequestDelegate, RequestDelegate>的形式存在List中 57 //Build的时候利用上面的List,会生成一个委托链。 } 60 catch (Exception ex) when (_options.CaptureStartupErrors) }
直接看BuildApplication()方法,
请求管道已经生成完毕,剩下的就是请HttpContext进入这个管道了,我们看看WebHost.Run()发生了什么
Host.Run()方法中发生了什么?
Host.Run()内部会调用Host.Start()方法,然后再在控制台输出一些信息,并且传入一个CancellationToken 允许随时中断程序。那么看来得去瞧瞧Host.Start()方法了。
Start() 2 { Server.Start(}
它调用了Server.Start()方法,从方法名上大概能猜出来是干嘛,具体细节留在有关Server的文章里面讲。去看看HostingApplication这个类:
HostingApplication : IHttpApplication<HostingApplication.Context> 2 { RequestDelegate _application; ILogger _logger; DiagnosticSource _diagnosticSource; IHttpContextFactory _httpContextFactory; Context CreateContext(IFeatureCollection contextFeatures){...} DisposeContext(Context context, Exception exception){...} Task ProcessRequestAsync(Context context) 13 { 14 return _application(context.HttpContext); 15 } Context 18 { 19 public HttpContext HttpContext { get; set; } 20 public IDisposable Scope { get; set; } StartTimestamp { get; set; } 22 }
显然它的作用就是配合Server去创建上下文,大概的过程就是
总结