asp.net core 3.1 entry: Main function in Program.cs

This article analyzes the running sequence of the code in the Main () function in Program.cs and analyzes the startup of the asp.net core program. The focus is not to analyze the source code, but to sort out the order in which the program starts. Which examples and French methods are used?

The program entry of asp.net core 3.1 is in the project Program.cs file, as follows.

ususing System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

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

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

1. Program

The program class is defined in the Program.cs file in the root directory of the project, and is the entry point for all .net core programs, including the asp.net core program. This is very interesting, a bit similar to the console program. Compared with the previous web project, there is no program entry only web.config, global and other configuration files and global files such as web entry without program entry, I think this type is easier to understand how asp.net core works.

In the Program class in asp.net core 3.1, two methods are defined: Main () and CreateHostBuilder ()

2. Main program entry Program.Main () method

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

The Main () method is the entry method of the entire project, just like the C series language, all program entries are. Here main () has only one line of code, but actually executes three functions C:

  1 IHostBuilder builder= CreateHostBuilder(args);
  2 IHost host=builder.Build();
  3 host.Run();

The first line is the CreateHostBuilder defined in the Program class. It mainly generates an IhostBuilder instance builder.

In the second line, an Ihost instance host is generated through the builder.Build () method.

The third part, through the host.Run () method, start running the web project, then you can respond to various requests.

The most cumbersome part of this process is the creation of builders, the focus of this article is here.

3. Create and configure the Host Builder: Program.CreateHostBuilder (args) method

Break down the definition of CreateHostBuilder (args)

This method is defined in the Pogram class through lamada expressions. Because it performs a sentence, it can be defined in this simple way (for anonymous functions, lamada, built-in delegates can refer to my previous article C # Anonymous methods (functions) anonymous delegates built-in generic delegate lamada 1 ). In order to facilitate reading, analyze the Main () method according to the above, so its actual definition is as follows:

  1         public static IHostBuilder CreateHostBuilder(string[] args)
  2         {
  3             IHostBuilder builder = Host.CreateDefaultBuilder(args);
  4             Action < IWebHostBuilder > configAction = delegate(IWebHostBuilder webBuilder)
  5             {
  6                 webBuilder.UseStartup<Startup>();
  7             };
  8             builder=builder.ConfigureWebHostDefaults(configAction);
  9             return builder;
 10         }

3.1. The birth of builder: generate IHostBuilder

Start with the French analysis of Host.CreateHostBuilder ()

The first line of code in the CreateHostBuilder () method is to call the Host.CreateDefaultBuilder (args) method to create an IBuilder object instance.

IHostBuilder builder = Host.CreateDefaultBuilder(args);

IHostBuilder is a very important example, only with this example can you continue to load more configuration operations. Produce IHost instances through IHostBuilder.Build (). Finally, run the project through IHost.Run ().

3.1.1 Host class-used to generate the initial builder static class

The Host class is a static class defined in the Microsoft.Extensions.Hosting namespace (the name is referenced in Program.cs ) . It is introduced in Program.cs.

The statement is as follows:

  1 using Microsoft.Extensions.Hosting;
  2 
  3 namespace Microsoft.Extensions.Hosting
  4 {
  5     public static class Host
  6     {
  7 	    public static IHostBuilder CreateDefaultBuilder();
  8         public static IHostBuilder CreateDefaultBuilder(string[] args);
  9     }
 10 }

One static method of the Host static class is CreateDefaultBuilder (). A total of 2 overload declarations: one with parameters and one without parameters. Reference source code ( .NET Core 3.0's in-depth source code understanding of Host (1) 2 ) The overload without parameters actually calls the parameter form with null as the parameter, as follows:

  1 public static IHostBuilder CreateDefaultBuilder() =>CreateDefaultBuilder(args: null);
3.1.2 Host.CreateDefaultBuilder(args)方法
Official description is initialized with default values preconfigured a Microsoft.Extensions.Hosting. HostBuilder Example ( Initializes The Microsoft.Extensions.Hosting.HostBuilder A new new instance of class with pre-Configured Defaults, see detail with reference to an official document 3 ).
Related operations are: setting the root directory ContentRootPath ; loading to Host. IConfiguration : environment variable EnvironmentName , command line parameter args, configuration file IConfiguration. [EnvironmentName] json; and loading the log module and so on.
For details, please refer to Reference Documents 2 and 3. Among them, .NET Core 3.0's in-depth source code understanding of Host (1) , the author has analyzed this method from the perspective of source code, and the official document Host.CreateDefaultBuilder method officially explains what the French side operates.

3.2. IHostBuilder transformed into IWebHostBuilder

Continue to analyze the Host.CreateHostBuilder () method. After the IHostBuilder instance is established in 3.1, the IHostBuilder instance will be transformed into a webhosting webbuilder (IWebHostBuilder) through the builder.ConfigureWebHostDefaults (Action <IWebHostBuilder>) method.

The IHoustBuilder.ConfigureWebHostDefaults (Action <IWebHostBuilder>) method is defined in the static class Microsoft.Extensions.Hosting.GenericHostBuilderExtensions (GenericHostBuilderExtensions.cs). This static class defines this static method.

3.2.1. ConfigureWebHostDefaults () parameter

The parameter configure here is a built-in delegate Action <IWebHostBuilder>, the definition of this delegate executes a line of code:
webBuilder.UseStartup<Startup>();

3.2.2. ConfigureWebHostDefaults () method definition

In fact, the ConfigureWebHostDefaults (Action <IWebHostBuilder>) method is an extension method of IHostBuilder (so the previous writing is not accurate, the builder parameter is missing, and it was omitted before).
In order to facilitate the reading method, the method code in 3. is analyzed as follows:
 
 
  1  	     public static IHostBuilder ConfigureWebHostDefaults(this IHostBuilder builder, Action<IWebHostBuilder> configure)
  2         {
  3             Action<IWebHostBuilder> webconfigure = delegate(IWebHostBuilder webHostBuilder)
  4             {
  5                 WebHost.ConfigureWebDefaults(webHostBuilder);
  6                 configure(webHostBuilder);
  7             };
  8             return builder.ConfigureWebHost(webconfigure);
  9         }
In fact, I called another extension class ConfigureWebHost (Action <IWebHostBuilder>) of IHostBuilder ( this extension method is defined in the static class of Microsoft.Extensions.Hosting.GenericHostWebHostBuilderExtensions ).

3.2.2.1 Turn IHostBuilder into IWebHostBuilder: builder.ConfigureWebHost (webconfigure) method

3.2.2.1.1 Action<IWebHostBuilder> webconfigure参数
Built-in delegation, where the delegation is defined, there are two main lines of code:
Configure the default web settings of IWebHostBuilder.
 
 
WebHost.ConfigureWebDefaults(webHostBuilder);
In core2.1, this method is called in WebHost.CreateDefaultBuilder (arg) in CreateHostBuilder (). After core3.1, changed to Host.ConfigureDefualts (arg), it is called in ConfigureWebHost by delegation. Because this method is called in the delegate, it will be described in detail when it is reduced to the execution of the delegate in the following section.
Call the parameters passed in the delegate
configure(webHostBuilder);
 Is in 3.2.1
 
 
webBuilder.UseStartup<Startup>();
The details are explained in the following chapters when entrusting execution.
3.2.2.1.2 builder.ConfigureWebHost (webconfigure) method definition
定义在Microsoft.Extensions.Hosting.GenericHostWebHostBuilderExtensions(GenericHostWebHostBuilderExtensions.cs) 
  1 using System;
  2 using Microsoft.AspNetCore.Hosting;
  3 using Microsoft.AspNetCore.Hosting.Internal;
  4 
  5 namespace Microsoft.Extensions.Hosting
  6 {
  7     public static class GenericHostWebHostBuilderExtensions
  8     {
  9         public static IHostBuilder ConfigureWebHost(this IHostBuilder builder, Action<IWebHostBuilder> configure)
 10         {
 11             var webhostBuilder = new GenericWebHostBuilder(builder);
 12             configure(webhostBuilder);
 13             return builder;
 14         }
 15     }
 16 }
Microsoft.AspNetCore.Hosting.Internal.GenericWebHostBuilder
In asp.net core 2.1 IWebHostBuilder in asp.net core 3.1 how to use generic IHostBuilder to produce webhost builder, and finally found it.  
Through Microsoft.AspNetCore.Hosting.Internal.GenericWebHostBuilder class instance. GenericWebHostBuilder is an internal class. There are very few online resources in this category, and even the instructions cannot be found in the official documentation, but you can refer to the source code of its source GenericWebHostBuilder.cs . Such declarations and their constructor declarations are as follows:
internal class GenericWebHostBuilder : IWebHostBuilder, ISupportsStartup, ISupportsUseDefaultServiceProvider
{
     public GenericWebHostBuilder(IHostBuilder builder);
}
This class is very important. It is the cornerstone or source of IHostBuilder transformed into IWebHostBuilder in Asp.net core 3.1 project. The first instance of IHostBuilder was instantiated by this kind of constructor and became IWebHostBuilder in 2.1. The actual thing is to inject some web-related services, it is recommended to check the source code in detail (refer to document 4 )
3.2.2.2 Configure Web-related parameters for IWebHostBuilder Commissioning parameters: finally commissioned
 
 
configure(webhostBuilder);
After so many layers of delegations were passed in, we finally got to the end. After implementing IHostBuilder to IWebHostBuilder, all the config-related delegations were finally executed
 
 
  1  // In builder.ConfigureWebHostDefaults () (-> in program.GreateHostBuilder ()) 
  2  // Introduce builder.ConfigureWebHost () as the delegate parameter with the next sentence code 
  3 WebHost.ConfigureWebDefaults (webHostBuilder);
   4  // 
Pass in builder.ConfigureWebHostDefaults () as a delegate parameter in Program.CreateHostBuilder ()   5  // Then pass builder.ConfigureWebHostDefaults () and close the sentence together as a delegate to builder.ConfigureWebHost () 
  6 webBuilder.UseStartup <Startup> ();
3.2.2.2.1 WebHost.ConfigureWebDefualts(IWebHostBuilder)方法:
This method is the last method called in WebHost.CreateDefaultBuilder (args) in Asp.net core 2.1, and in Asp.net core 3.1, after calling IWebHostBuilder as a generic IHostBuilder, the callback delegate is executed when IHostBuilder.ConfigureWebHost () is executed carried out. This method is similar to Host.CreateDefaultBuilder (args), using pre-configuration to configure some parameters about the Web mode. Mainly to inject some web related services, configure the host address and so on. There is no official documentation for this method. It is recommended to directly check the source code of WebHost.cs (refer to document 5 ).
3.2.2.2.2 webBuilder.UseStartup<Startup>()法方:
UseStartup () is an extension release of webbuilder, defined in the static class of Microsoft.AspNetCore.Hosting.WebHostBuilderExtensions (WebHostBuilderExtensions.cs), this method is declared as follows
public static IWebHostBuilder UseStartup(this IWebHostBuilder hostBuilder, Type startupType)

It can be seen from the method name that the Startup class is used. This method mainly uses reflection technology to reflect the Startup class and respond to the configuration information in the startup class.

3.3. Finally, sort out the core code of the builder

1.IHostBuilder builder = Host.CreateDefaultBuilder(args);
Create a basic builder (read app.json)
2.IWebHostBuilder webHostBuilder= new GenericWebHostBuilder(builder);
Convert to webbuilder
3.WebHost.ConfigureWebDefaults(webHostBuilder);
Use pre-default configuration for webbuilder
4.webBuilder.UseStartup<Startup>();
Read startup class configuration information

4. Summary

The startup code of aps.net core 3.1 is analyzed. There are three basic concepts to create a builder, generate a host through the builder, and finally use the host to execute it. Among them, builder and builder configuration, host host are important concepts. The difference between core 3.1 and core 2.1 is to abstract an IHostBuilder from IWebHostBuilder. The code of core 3.1 can be more flexible, and future services can be more than web services.
In addition, asp.net core's builder configuration can see a lot of very dependent, control reversal technology is injection dependency, the advantage is that you want to register what services you want, more flexible.
If you want to study in depth, it is recommended to refer to the following articles:

1. In- depth source understanding of .NET Core 3.0 Host (1)
2. In- depth source understanding of .NET Core 3.0 Host (2)
  The author's 2 articles introduce the relevant knowledge of Ihostbuilder from the source point of view
3. Official document: .NET Universal Host Explain the knowledge of IHostBuilder
4. Official document: Application startup in ASP.NET Core Introduces related knowledge of startup class


Reference documents:
1. C # anonymous methods (functions) anonymous delegate built generic delegate lamada Author: edzjx
2. the .NET 3.0 Core source of deep understanding Host (a) Author: Ai Xin
3. Official documents Host.CreateDefaultBuilder method of: Micrsoft official documents
4. GenericWebHostBuilder.cs source code authors: Asp.net@github 
5. WebHost.cs source code authors: Asp.net@github 
6. the .NET 3.0 Core source of deep understanding Host (two) Author: Ai Xin
7. The official documentation: .NET Universal Host Author: Micrsoft official documents
8. Official documents: application starts in ASP.NET Core Author: Micrsoft official documents

Guess you like

Origin www.cnblogs.com/alannever/p/12733268.html