
前一篇提到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 Add@R_301_968@s(serviceCollection2,hostingServiceProvIDer);26 WebHost webHost = new WebHost(serviceCollection2,hostingServiceProvIDer,_options,_config,hostingStartupErrors);27 try28 {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() > 133 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 catch40 {41 webHost.dispose();42 throw;43 }44 }45 throw new InvalIDOperationException(Resources.WebHostBuilder_SingleInstance);46 }VIEw Code
这个方法中有几个笔记重要的部分,下面我给标记一下
调用BuildCommonServices私有方法主要是注入一些程序所需的基础组件,请看源代码:
1 private IServiceCollection BuildCommonServices(out AggregateException hostingStartupErrors) 2 { 3 hostingStartupErrors = null; 4 _options = new WebHostoptions(_config,Assembly.GetEntryAssembly()?.Getname().name); 5 if (!_options.PreventHostingStartup) 6 { 7 List<Exception> List = new List<Exception>(); 8 foreach (string item in _options.GetFinalHostingStartupAssemblIEs().distinct(StringComparer.OrdinalignoreCase)) 9 {10 try11 {12 foreach (HostingStartupAttribute customAttribute in Assembly.Load(new Assemblyname(item)).GetCustomAttributes<HostingStartupAttribute>())13 {14 ((IHostingStartup)Activator.CreateInstance(customAttribute.HostingStartupType)).Configure(this);15 }16 }17 catch (Exception innerException)18 {19 List.Add(new InvalIDOperationException("Startup assembly " + item + " Failed to execute. See the inner exception for more details.",innerException));20 }21 }22 if (List.Count > 0)23 {24 hostingStartupErrors = new AggregateException(List);25 }26 }27 string contentRootPath = ResolveContentRootPath(_options.ContentRootPath,AppContext.BaseDirectory);28 _hostingEnvironment.Initialize(contentRootPath,_options);29 _context.HostingEnvironment = _hostingEnvironment;30 ServiceCollection serviceCollection = new ServiceCollection();31 serviceCollection.AddSingleton(_options);32 ((IServiceCollection)serviceCollection).AddSingleton((IHostingEnvironment)_hostingEnvironment);33 ((IServiceCollection)serviceCollection).AddSingleton((Microsoft.Extensions.Hosting.IHostingEnvironment)_hostingEnvironment);34 serviceCollection.AddSingleton(_context);35 IConfigurationBuilder configurationBuilder = new ConfigurationBuilder().SetBasePath(_hostingEnvironment.ContentRootPath).AddConfiguration(_config);36 foreach (Action<WebHostBuilderContext,IConfigurationBuilder> configureAppConfigurationBuilderDelegate in _configureAppConfigurationBuilderDelegates)37 {38 configureAppConfigurationBuilderDelegate(_context,configurationBuilder);39 }40 IConfigurationRoot configurationRoot = configurationBuilder.Build();41 ((IServiceCollection)serviceCollection).AddSingleton((IConfiguration)configurationRoot);42 _context.Configuration = configurationRoot;43 DiagnosticListener implementationInstance = new DiagnosticListener("Microsoft.AspNetCore");44 serviceCollection.AddSingleton(implementationInstance);45 ((IServiceCollection)serviceCollection).AddSingleton((DiagnosticSource)implementationInstance);46 serviceCollection.AddTransIEnt<IApplicationBuilderFactory,ApplicationBuilderFactory>();47 serviceCollection.AddTransIEnt<IhttpContextFactory,httpContextFactory>();48 serviceCollection.AddScoped<IMIDdlewareFactory,MIDdlewareFactory>();49 serviceCollection.AddOptions();50 serviceCollection.AddLogging();51 serviceCollection.AddTransIEnt<IStartupFilter,autoRequestServicesstartupFilter>();52 serviceCollection.AddTransIEnt<IServiceProvIDerFactory<IServiceCollection>,DefaultServiceProvIDerFactory>();53 serviceCollection.AddSingleton<ObjectPoolProvIDer,DefaultObjectPoolProvIDer>();54 if (!string.IsNullOrEmpty(_options.StartupAssembly))55 {56 try57 {58 Type startupType = StartupLoader.FindStartupType(_options.StartupAssembly,_hostingEnvironment.Environmentname);59 if (IntrospectionExtensions.GetTypeInfo(typeof(IStartup)).IsAssignableFrom(startupType.GetTypeInfo()))60 {61 serviceCollection.AddSingleton(typeof(IStartup),startupType);62 }63 else64 {65 serviceCollection.AddSingleton(typeof(IStartup),delegate (IServiceProvIDer sp)66 {67 IHostingEnvironment requiredService = sp.GetrequiredService<IHostingEnvironment>();68 return new ConventionBasedStartup(StartupLoader.LoadMethods(sp,startupType,requiredService.Environmentname));69 });70 }71 }72 catch (Exception source)73 {74 ExceptiondispatchInfo capture = ExceptiondispatchInfo.Capture(source);75 ((IServiceCollection)serviceCollection).AddSingleton((Func<IServiceProvIDer,IStartup>)delegate76 {77 capture.Throw();78 return null;79 });80 }81 }82 foreach (Action<WebHostBuilderContext,IServiceCollection> configureServicesDelegate in _configureServicesDelegates)83 {84 configureServicesDelegate(_context,serviceCollection);85 }86 return serviceCollection;87 }VIEw Code
这个方法中其中就包含了注入IConfiguration的代码和构建IServiceCollection容器的代码,当然还有一些其他的主要中间件注入啊IApplicationBuilderFactory,包括httpContextFactory等等都在这个方法里面被IServiceCollection容器管理,具体请看下图
这里讲清楚之后,我们直接进入UseStartup方法中,这个方法是注入了Startup的实例,请看主要源代码
@H_502_787@1 public static IWebHostBuilder UseStartup(this IWebHostBuilder hostBuilder,Type startupType) 2 { 3 string name = startupType.GetTypeInfo().Assembly.Getname().name; 4 return hostBuilder.UseSetting(WebHostDefaults.ApplicationKey,name).ConfigureServices(delegate (IServiceCollection services) 5 { 6 if (IntrospectionExtensions.GetTypeInfo(typeof(IStartup)).IsAssignableFrom(startupType.GetTypeInfo())) 7 { 8 services.AddSingleton(typeof(IStartup),startupType); 9 }10 else11 {12 services.AddSingleton(typeof(IStartup),delegate (IServiceProvIDer sp)13 {14 IHostingEnvironment requiredService = sp.GetrequiredService<IHostingEnvironment>();15 return new ConventionBasedStartup(StartupLoader.LoadMethods(sp,requiredService.Environmentname));16 });17 }18 });19 }VIEw Code
上面只是被IServiceCollection所管理 并没有真正起作用,真正调用的是Main方法中的Build().Run(),这里的Build就是上面那个IWebHostBuilder中的主要的构建方法,而Run则是正式启动应用程序和调用Startup中的ConfigureServices方法
请看代码:
分享Program类的过程大致就到这里了
总结以上是内存溢出为你收集整理的.net core mvc启动顺序以及主要部件2全部内容,希望文章能够帮你解决.net core mvc启动顺序以及主要部件2所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)