ASP.NET CORE系列【七】分析NetCore启动原理

  • 2019 年 10 月 3 日
  • 筆記

前言

 有很久一段时间没更新了,因为工作和家里的问题导致没能坚持,

现在开始会继续每周更新,主要是记录自己所学和一起讨论解决过的问题,一起成长,

为.net圈子添砖加瓦!

介绍

到目前为止应该很多同学已经把项目升级到core了,对于项目结构都已经很熟悉了,今天我们主要讲解Startup.Cs   Program.Cs两个文件

分析Core项目的启动原理

 

Program.Cs

 

 

   很熟悉Main入口,主要是三个方法CreateWebHostBuilder()    Build()  Run()  很简单的三个方法,但是他却能够顺利的把整个项目给启动起来

   它肯定是在内部封装了很多东西,那它是如何封装的呢  是如何运行的

    一.首先我们得学会查看源码

     1.https://github.com/aspnet/AspNetCore

     2.Vs2019

     3.Reshaper

      这里有三个方法查看netcore源代码,第一个就是微软官方开源的项目地址

      今天我们主要讲使用Vs2019方法,Reshaper不建议去使用,电脑配置不高的情况下会很卡,而且vs2019的新功能也基本上够用了

     使用vs2019先设置   工具->选项->文本编辑器->c#->高级->支持导航到反编译(实验)

    勾上之后,按f12就能定位到源码

 

二.启动顺序

 1 Main()入口   

 

 2 WebHostBuilder()准备 

     CreateDefaultBuilder方法 从命名就能看出,它注入了很多服务,大家可以定位进入仔细看看

     创建WebHost默认配置,加载自定义配置UseStartup()主要在Startup.cs里面自行配置

    主要是配置Service Di和http管道,这些都市在WebHost启动之前做的事

    我们f12定位打源代码查看

 1 public static IWebHostBuilder CreateDefaultBuilder(string[] args)   2         {   3             WebHostBuilder webHostBuilder = new WebHostBuilder();   4             if (string.IsNullOrEmpty(webHostBuilder.GetSetting(WebHostDefaults.ContentRootKey)))   5             {   6                 webHostBuilder.UseContentRoot(Directory.GetCurrentDirectory());   7             }   8             if (args != null)   9             {  10                 webHostBuilder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build());  11             }  12             webHostBuilder.UseKestrel(delegate (WebHostBuilderContext builderContext, KestrelServerOptions options)  13             {  14                 options.Configure(builderContext.Configuration.GetSection("Kestrel"));  15             }).ConfigureAppConfiguration(delegate (WebHostBuilderContext hostingContext, IConfigurationBuilder config)  16             {  17                 IHostingEnvironment hostingEnvironment = hostingContext.HostingEnvironment;  18                 config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).AddJsonFile("appsettings." + hostingEnvironment.EnvironmentName + ".json", optional: true, reloadOnChange: true);  19                 if (hostingEnvironment.IsDevelopment())  20                 {  21                     Assembly assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName));  22                     if (assembly != null)  23                     {  24                         config.AddUserSecrets(assembly, optional: true);  25                     }  26                 }  27                 config.AddEnvironmentVariables();  28                 if (args != null)  29                 {  30                     config.AddCommandLine(args);  31                 }  32             }).ConfigureLogging(delegate (WebHostBuilderContext hostingContext, ILoggingBuilder logging)  33             {  34                 logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));  35                 logging.AddConsole();  36                 logging.AddDebug();  37                 logging.AddEventSourceLogger();  38             })  39                 .ConfigureServices(delegate (WebHostBuilderContext hostingContext, IServiceCollection services)  40                 {  41                     services.PostConfigure(delegate (HostFilteringOptions options)  42                     {  43                         if (options.AllowedHosts == null || options.AllowedHosts.Count == 0)  44                         {  45                             string[] array = hostingContext.Configuration["AllowedHosts"]?.Split(new char[1]  46                             {  47                                 ';'  48                             }, StringSplitOptions.RemoveEmptyEntries);  49                             options.AllowedHosts = ((array != null && array.Length != 0) ? array : new string[1]  50                             {  51                                 "*"  52                             });  53                         }  54                     });  55                     services.AddSingleton((IOptionsChangeTokenSource<HostFilteringOptions>)new ConfigurationChangeTokenSource<HostFilteringOptions>(hostingContext.Configuration));  56                     services.AddTransient<IStartupFilter, HostFilteringStartupFilter>();  57                 })  58                 .UseIIS()  59                 .UseIISIntegration()  60                 .UseDefaultServiceProvider(delegate (WebHostBuilderContext context, ServiceProviderOptions options)  61                 {  62                     options.ValidateScopes = context.HostingEnvironment.IsDevelopment();  63                 });  64             return webHostBuilder;  65         }

View Code

 3 Build()构建   

   构建AspNetCre.Hosting 托管web应用程序

 4 Run()启动

   运行web应用程序并阻止调用线程,直到主机关闭

   

 

CreateDefaultBuilder方法

 说一下默认配置 配置了哪些东西,结合代码看一下

 第一行   WebHostBuilder webHostBuilder = new WebHostBuilder(); 创建了webHostBuilder实例,我们F12进去看看

 类里面的默认构造函数,看到这里,构造函数实例对象(依赖注入)

  

 

 

 

 

 我们这里可以看到 提供了ApplicationBuilder工厂  然后把我们各种配置在这里进行直接注入了

 在Starpup.cs里面 app.UseMvc() 这种  都是IApplicationBuilder

 现在恍然大悟了

具体工厂里有什么呢,接口怎么定义呢,大家有兴趣可以自行去了解

 

第二行  webHostBuilder.UseContentRoot(Directory.GetCurrentDirectory());

 Use是一个中间件,ContentRoot是我们内容的根目录,指定了了我们web主机要使用的内容站点根目录

这个设置决定了安排asp.net core开始搜索内容文件,比如view

也就是说 项目启动,肯定有一个中间件去调用wwwroot这个文件夹

 

后面还有UseConfiguration中间件  使用一些命令 比如dootnet run 在这里执行     

 UseKestrel  这是开启Kestrel中间件  给web主机使用的服务器,后面代码又开启了UseIIs的中间件

可能会疑惑为什么会开启不同的呢,

这里主要是,netcore有两种运营模式 一个进程内 一个是进程外,这个后续的文章会降到

看大这里,大家应该都知道.net core启动是个怎么回事了,剩下的 可以自行看源码了解哦

 

ps:码字水平有待提高!