1 Introduction

For ASP.NET Core applications, it’s important to remember that it’s essentially a standalone console application that doesn’t have to be hosted inside IIS and doesn’t require IIS to start running (and this 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’s hosting or self-hosting, you can’t do without Host . In the ASP.NET Core application, configure and start a Host to complete the application startup and its lifecycle management (as shown below). The main responsibility of Host is the configuration of Web Server and the construction of Pilpeline (Request Processing Pipeline) .

ASP.NET_Core__basic_series(3)_the_startup_process_1.png

ASP.NET Core overall startup process

This picture depicts an overall startup process. From the above figure, we know that the startup of an ASP.NET Core application consists of three main steps:

  1. CreateDefaultBuilder(): Create IWebHostBuilder
  2. Build(): IWebHostBuilder is responsible for creating IWebHost
  3. Run(): Start IWebHost

Therefore, the startup of an ASP.NET Core application essentially starts the WebHost object that is hosted.
It involves two key objects IWebHostBuilderand IWebHosttheir internal implementation is at the heart of the ASP.NET Core application. Let’s take a look at the source code and comb the call stack to find out!

2. Host Constructor: IWebHostBuilder

Before starting the IWebHosthost, we need to complete IWebHostthe creation and configuration of the pair . This work needs to IWebHostBuilderbe done with the help of objects, the default implementation is provided in ASP.NET Core WebHostBuilder. And WebHostBuilderby the same name WebHost tools (Microsoft.AspNetCore under the name space) of the CreateDefaultBuildermethod of creation.

ASP.NET_Core__basic_series(3)_the_startup_process_2.png

CreateDefaultBuilder() call stack

From the above picture we can see that the CreateDefaultBuilder()method has mainly done six major things:

  1. UseKestrel: Use Kestrel as the web server.
  2. UseContentRoot: Specifies the content root (content root) used by the web host, such as Views. The default is the current application root directory.
  3. ConfigureAppConfiguration: Sets the current application configuration. Mainly read the appsettinggs.json configuration file, UserSecrets configured in the development environment, add environment variables and command line parameters.
  4. ConfigureLogging: Read the Logging node in the configuration file and configure the logging system.
  5. UseIISIntegration: Use IISIntegration middleware.
  6. UseDefaultServiceProvider: Sets the default dependency injection container.

After the creation is completed WebHostBuilder, the UseStartup()startup class is specified by calling to provide an entry for the registration of the subsequent service and the registration of the middleware.

3. Host: IWebHost

IWebHostThe host used to represent the web application is defined in ASP.Net Core and provides a default implementation WebHost. Create a host by calling IWebHostBuilderthe Build()method to complete. So what do you do with this method? Let’s take a look at the yellow border in the ASP.NET Core Startup Process Call Stack:

ASP.NET_Core__basic_series(3)_the_startup_process_3.png

ASP.NET Core startup process call stack

The core is mainly the creation of WebHost, which can be divided into three parts:

  1. Build a dependency injection container, the registration of the initial generic service: BuildCommonService();
  2. Instantiate WebHost: var host = new WebHost(…);
  3. Initialize WebHost, which is to construct a request processing pipeline consisting of middleware: host.Initialize();

3.1. Registering the initial general service

BuildCommonServiceThe method mainly does two things:

  1. Find HostingStartupAttributefeatures to apply launch configurations in other assemblies
  2. Registered general service
  3. If the startup assembly is configured, it is found and IStartupinjected into the IOC container as a type.

3.2. Creating IWebHost

public IWebHost Build()
{
    
    var host = new WebHost(
        applicationServices,
        hostingServiceProvider,
        _options,
        _config,
        hostingStartupErrors);
    }
    
    host.Initialize();

    return host;
}

3.3. Build request processing pipeline

The construction of the request pipeline is mainly the connection processing between the middleware.

The construction of the request processing pipeline has three main parts:

  1. Register the service bound in the Startup;
  2. Configure IServer;
  3. Build a pipeline

The construction of the request pipeline is mainly by means IApplicationBuilderof the related class diagram as follows:

ASP.NET_Core__basic_series(3)_the_startup_process_4.png

Request pipeline construction

4. Start WebHost

The start of WebHost is mainly divided into two steps:

  1. Reconfirm that the request pipeline was created correctly
  2. Start Server to listen for requests
  3. Start HostedService

ASP.NET_Core__basic_series(3)_the_startup_process_5.png

Start the WebHost call stack

4.1. Confirm the creation of the request pipeline

As can be seen from the figure, the first Initialize()method of calling is mainly to ensure the correct creation of the request pipeline. The internal is mainly BuildApplication()the call to the method, which has the same call stack as the WebHost build link we mentioned above. The final return is RequestDelegatethe request pipeline represented by the type of middleware .

4.2. Starting Server

Let’s first look at the class diagram:

ASP.NET_Core__basic_series(3)_the_startup_process_6.png

IServer class diagram

From the class diagram we can see that the IServerinterface mainly defines a read-only property collection property, a method declaration for starting and stopping. When creating the host constructor IWebHostBuilderwe UseKestrel()specified the use of KestrelServer as the default IServer implementation by calling the method. The method declaration receives a IHttpApplication<TContext> applicationparameter. From the naming point of view, it represents an Http application. Let’s look at the specific interface definition:

ASP.NET_Core__basic_series(3)_the_startup_process_7.png

IHttpApplication class diagram

It mainly defines three methods, the first method is used to create the request context; the second method is used to process the request; the third method is used to release the context. As for the request context, it is the core parameter used to carry the request and return the response, which runs through the entire request processing pipeline. The default implementation is provided in ASP.NET Core HostingApplication, whose constructor receives a RequestDelegate _applicationprocessing pipeline (that is, the processing pipeline formed by the link middleware) to process the request.

var httpContextFactory = _applicationServices.GetRequiredService<IHttpContextFactory>();
var hostingApp = new HostingApplication(_application, _logger, diagnosticSource, httpContextFactory);

4.3. Starting IHostedService

IHostedServiceThe interface is used to define the background task. By implementing the interface and registering it in the Ioc container, it will start as the ASP.NET Core program starts, terminate and terminate.

5. Summary

Combined with the source code, through the combing of the call stack of ASP.NET Core, the overall context of the startup process is clear at a glance, and the main key objects are known:

  1. The host constructor IWebHostBuilder responsible for creating IWebHost
  2. Representing the host’s IWebHost interface
  3. IApplicationBuilder for building request pipes
  4. RequestDelegate connected by middleware
  5. IServer interface representing Web Server
  6. Request context HttpContext throughout the request processing pipeline
  7. IHostedService interface that can be used to register background services

This section first has a basic understanding of the operating principle of ASP.NET Core in general, and then we will explain these core objects one by one to deepen understanding.

Orignal link:https://www.jianshu.com/p/caa1a1a68611