ASP.NET CORE boot process and interpret source

In this particular New Year, we believe you can not have a home, have a distance to go to work the day back in town, but because of a bat's impossible for us to go back to work, we may have telecommuting from home, some at home lying down reading, playing some games at home; in this particular boring logs, I opened the decisive interpretation and learning shared wifi traffic to .net core 3.1 source code from boring in bed, and to learn to share something for everyone .

doubt

New to ASP.NET CORE project students may have the following questions:

  • Start the process ASP.NET CORE project is kind of how?
  • Why ASP.NET CORE project could start in the console after running into a web application?

Now here I use .NETCORE 3.1 parse the latest stable release version to the above question, with everyone wondering solve the above problems, you can learn to ASP.NETCORE finished project will have a different understanding and insight.


Boot process

New to ASP.NET core of the students will feel and estimates before the design is quite different ASP.NET, code style there are big changes before ASP.NET is a family bucket frame mode, which contains all of the realization that you to the use of less than all integrated in it; however ASP.NET CORE framework made big changes to minimize abstract design, ease of use, complete the expansion by extending the method.

Reading through the source code can be found most of the students are the smallest unit api abstract interface approach to design, other complex methods are extended api provided by the extension method, which is a major advantage of .NET Core reason efficient and easy to expand .

For ASP.NET Core applications, we have to remember a very important point is: it is essentially a stand-alone console application, it is not necessary to hosted inside IIS and IIS is not required to start the run (which It is the cornerstone of ASP.NET Core cross-platform). ASP.NET Core applications have a built-in Self-Hosted (self-hosted) of the Web Server (Web server) , to handle external requests.

Whether it is hosted or self-hosted, they are inseparable from the Host (the host) . In ASP.NET Core applications to complete and launch the application life cycle management by configuring and start a Host. The main responsibility is to Web Server Host Configuration and Pilpeline (request processing pipeline) built.

We will now create a ASP.NETCORE WEB project steps

File -> New -> Project -> Select ASP.Net Core Web Applications -> Select .NETCORE 3.1 Framework Figure:

2.png

After creating a project, we can see the following code from the Program class:

public class Program
{
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)//开启一个默认的通用主机Host建造者
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    // 从前缀为“ASPNETCORE” 环境变量加载WEB主机配置
                    // 默认是Kestrel 设置为web 服务器并对其进行默认配置, 支持iis集成
                    //注册系统启动所使用的组件,比如配置的组件,容器的组件等
                    webBuilder.UseStartup<Startup>();
                });
}

Check the above code can be found in the Main method code is very simple, clearly visible

CreateHostBuilder(args): Method creates a IHostBuilder abstract object creation process include CreateDefaultBuilder(args): open creates a default generic host Host builders, and through the ConfigureWebHostDefaults()method of configuring the default to open Kestrelthe default Web server and its default configuration, and integration of the integration of iis

Build(): Responsible for creating IHost, students read the source code can be found in Buildthe process will configure a variety of things, itself, a series of pipeline mode by default or custom configuration and build service registration (explained in detail below)

Run() : Start IHost

So, start nature ASP.NET Core application is to start Host object as the host.

Which is mainly related to two key objects IHostBuilderand IHosttheir internal implementation is the core ASP.NET Core applications. Here we combine combing the call stack and source code to find out!

Detailed source code is as follows:

asp.net core boot process source code .png

From the figure above we can see that CreateDefaultBuilder()the method worked five main events:
  • UseContentRoot: Specify the Web host to use content root (the contents of the root directory), such as Views. The default for the current application root directory.
  • ConfigureHostConfiguration :启动时宿主机需要的环境变量等相关,支持命令行
  • ConfigureAppConfiguration:设置当前应用程序配置。主要是读取 appsettinggs.json 配置文件、开发环境中配置的UserSecrets、添加环境变量和命令行参数 。
  • ConfigureLogging:读取配置文件中的Logging节点,配置日志系统。
  • UseDefaultServiceProvider:设置默认的依赖注入容器。
从图中可以看出CreateDefaultBuilder 后调用了ConfigureWebHostDefaults 方法,该方法默认主要做了以下几个事情
  • UseStaticWebAssets:静态文件环境的配置启用
  • UseKestrel:开启Kestrel为默认的web 服务器.
  • ConfigureServices:服务中间件的注册,包含路由的中间件的注册
  • UseIIS:对iis 集成的支持
  • UseStartup:程序Startup 启动,该启动类中可以注册中间件、扩展第三方中间件,以及相关应用程序配置的处理等等操作
现在所有的配置都已经配置创建好了,接下来我们来看看Build 方法主要做了哪些不为人知的事情,先来看下源代码
/// <summary>
        /// Run the given actions to initialize the host. This can only be called once.
        /// </summary>
        /// <returns>An initialized <see cref="IHost"/></returns>
        public IHost Build()
        {
            if (_hostBuilt)
            {
                throw new InvalidOperationException("Build can only be called once.");
            }
            _hostBuilt = true;

            BuildHostConfiguration();
            CreateHostingEnvironment();
            CreateHostBuilderContext();
            BuildAppConfiguration();
            CreateServiceProvider();

            return _appServices.GetRequiredService<IHost>();
        }

从代码中可以发现有一个_hostBuilt 的变量,细心的同学可以发现该变量主要是用于控制是否build 过,所以这里可以大胆猜测只能build 一次该Host;现在看下源代码解析图:
3.1 IHost Build Process .png

经过查看源代码得到的执行结构如上,因此我把代码改造成如下结构。

public class Program
{
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)//开启一个默认的通用主机Host建造者
                .ConfigureAppConfiguration(config => {
                    //注册应用程序内所使用的配置文件,比如数据库链接等等
                    Console.WriteLine("ConfigureAppConfiguration");
                })
                .ConfigureServices(service =>
                {
                    //注册服务中间件等操作
                    Console.WriteLine("ConfigureServices");
                })
                .ConfigureHostConfiguration(builder => {
                    //启动时需要的组件配置等,比如监听的端口 url地址等
                   Console.WriteLine("ConfigureHostCOnfiguration");
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
}

Startup 代码如下:

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            Console.WriteLine("Startup ");
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            Console.WriteLine("ConfigureServices");
            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            Console.WriteLine("Configure");
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

通过执行发现执行代码顺序正如我们源代码的执行顺序一致,执行顺序如下图:

3.png

为何通过控制台命令运行后自动启动了一个网站程序?

以前ASP.NET web项目是需要搭建在iis 中托管运行,但是ASP.NETCORE 项目可以直接通过命令行进行托管运行,运行后可以直接浏览器打开,你们有没有考虑过为什么?,细心的同学查看项目属性也会发现项目的输出类型也是控制台项目,如图:

1.png

查看这图,有没有发现很神奇,为什么输出类型竟然可以通过控制台命令行进行启动项目呢?

image.png

In the above source code analysis can be found in the course will start when you start a Kestrelserver ( ConfigureWebHostDefaultsmethod calls UseKestrellater), so start a console application command equivalent to an web server; briefly summarized under the following Kestreladvantages servers :

  • Kestrel: Kestrel is streamlined and efficient HttpServer, is provided in the form of packets, itself can not be run separately.

Inside the package for the libuvcall, as I / O ground floor, shielding the underlying implementation differences in each system; With Kestrel can be truly realized 跨平台.
Well, presumably the students here have a clear answer to the above two confused. Here I throw a question, read the interpretation of the code above, we have not found ASP.NET and ASP.NET CORE has been very different, which is what kind of design to improve it? Stay tuned for the next issue we work together to learn ASP.NET CORE - drilled 管道模型.

If you think writing is not bad, so stay tuned micro-channel public number:
Dr. .NET

Guess you like

Origin www.cnblogs.com/jlion/p/12392327.html