【NetCore】02-NetCore启动过程

文章目录

  • Asp.NetCore启动过程
    • 1.Program类
    • 2.Start Up

Asp.NetCore启动过程

1.Program类

Main函数调用CreateHostBuilder()方法,而CreateHostBuilder()返回了IHostBuilder,IHostBuilder就是应用程序启动的核心接口

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

	public static IHostBuilder CreateHostBuilder(string[] args)=>
		Host.CreateDefaultBuilder(args)
		.ConfigureAppConfiguration(builder=>{
			Console.WriteLine("ConfigureAppConfiguration");
		})
		.ConfigureServices(builder=>{
			Console.WriteLine("ConfigureServices");
		})
		.ConfigureHostConfiguration(builder=>{
			Console.WriteLine("ConfigureHostConfiguration");
		})
		.ConfigureWebHostDefaults(webBuilder=>{
			Console.WriteLine("ConfigureWebHostDefaults");
			webBuilder.UseStartup();
	})
}

2.Start Up

  • 组成:
    1.构造函数
    2.ConfigureServices()
    3.Configure()
public class Startup
{
	public Startup(Iconfiguration configuration)
	{
		Console.WriteLine("Startup.Startup");
		Configureation = configuration;
	}
	
	public IConfiguration Configuration {get;set;}
	
	// 服务注册
	public void ConfigureServices(IServiceCollection services)
	{
		Console.WriteLine("Startup.ConfigureServices");
		services.AddControllers();
	}
	
	// 注册中间件
	public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
	{
		Console.WriteLine("Startup.Configure");
		....
		
	}
}

  • 启动运行,输出结果如下:
ConfigureWebHostDefaults
ConfigureHostConfiguration
ConfigureAppConfiguration
ConfigureServices
Startup.Startup
Startup.ConfigureServices
Startup.Configure
  • 说明:

执行顺序
1.ConfigureWebHostDefaults
注册程序必要的几个组件,如配置组件,容器组件

2.ConfigureHostConfiguration
配置应用程序启动是必要的配置。比如需要监听的端口,监听的URL地址,这里也可以嵌入自己的个性化配置内容,注入到框架中

3.ConfigureAppConfiguration
用来配置我们自己的配置文件,供应用程序来读取。这些配置将在后续应用程序执行过程中间被每个组件读取

4.ConfigureServices、ConfigureLogging、Startup、Startup.ConfigureServices
用来往容器中注册注入我们的应用的组件

5.Startup.Configure
用来注入中间件,处理HttpContext整个请求过程的


这里在Program中的webBuilder.UseStartup();代码不是必需的,只是为了让代码结构更合理。可以在CreateHostBuilder直接进行Configure和ConfigureServices注册

public static IHostBuilder CreateHostBuilder(string[] args)=>
		Host.CreateDefaultBuilder(args)
		.ConfigureAppConfiguration(builder=>{
			Console.WriteLine("ConfigureAppConfiguration");
		})
		.ConfigureServices(builder=>{
			Console.WriteLine("ConfigureServices");
		})
		.ConfigureHostConfiguration(builder=>{
			Console.WriteLine("ConfigureHostConfiguration");
		})
		.ConfigureWebHostDefaults(webBuilder=>{
			Console.WriteLine("ConfigureWebHostDefaults");
				webBuilder.ConfigureServices(services=>{
					services.AddController();
				});
				webBuilder.Configure(app=>{
				})
			// webBuilder.UseStartup();
	})

你可能感兴趣的:(NetCore,.netcore)