要了解程序的運行原理,就要先知道程序的進入點及生命週期。以往ASP.NET MVC的啓動方式,是繼承 HttpApplication 做爲網站開始的進入點,而ASP.NET Core 改變了網站的啓動方式,變得比較像是 Console Application。git
本篇將介紹ASP.NET Core 的程序生命週期 (Application Lifetime) 及捕捉 Application 中止啓動事件。github
.NET Core 把 Web 及 Console 項目都處理成同樣的啓動方式,默認以 Program.cs 的 Program.Main
做爲程序入口,再從程序入口把 ASP.NET Core 網站實例化。我的以爲比ASP.NET MVC 繼承 HttpApplication
的方式簡潔許多。web
經過 .NET Core CLI 建立的 Program.cs 內容大體以下:
Program.csapp
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace MyWebsite
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
Program.Main
經過 BuildWebHost 方法取得 WebHost 後,再運行 WebHost;WebHost 就是 ASP.NET Core 的網站實例。async
當網站啓動後,WebHost會實例化 UseStartup 設置的Startup類,而且調用如下兩個方法:網站
經過 .NET Core CLI生成的Startup.cs 內容大體以下:ui
Startup.csthis
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace MyWebsite
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
}
Configure
方法的參數並不固定,參數的實例都是從 WebHost 注入進來,可依需求增減須要的參數。對 WebHost 來講 Startup.cs 並非必要存在的功能。
能夠試着把 Startup.cs 中的兩個方法,都改爲在 WebHost Builder 設置,變成啓動的前置準備。以下:spa
Program.cs3d
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace MyWebsite
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
// ...
})
.Configure(app =>
{
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
})
.Build();
}
}
把 ConfigureServices
及 Configure
都改到 WebHost Builder 註冊,網站的執行結果是同樣的。
二者之間最大的不一樣就是調用的時間點不一樣。
但
Configure
沒法使用除了IApplicationBuilder
之外的參數。
由於在 WebHost 實例化前,本身都還沒被實例化,怎麼可能會有有對象能注入給Configure
。
除了程序進入點外,WebHost的啓動和中止也是網站事件很重要一環,ASP.NET Core不像ASP.NET MVC用繼承的方式捕捉啓動及中止事件,而是透過Startup.Configure
注入IApplicationLifetime
來補捉Application啓動中止事件。
IApplicationLifetime
有三個註冊監聽事件及終止網站事件能夠觸發。以下:
public interface IApplicationLifetime
{
CancellationToken ApplicationStarted { get; }
CancellationToken ApplicationStopping { get; }
CancellationToken ApplicationStopped { get; }
void StopApplication();
}
經過Console輸出執行的過程,示例以下:
Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace MyWebsite
{
public class Program
{
public static void Main(string[] args)
{
Output("Application - Start");
var webHost = BuildWebHost(args);
Output("Run WebHost");
webHost.Run();
Output("Application - End");
}
public static IWebHost BuildWebHost(string[] args)
{
Output("Create WebHost Builder");
var webHostBuilder = WebHost.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
Output("webHostBuilder.ConfigureServices - Called");
})
.Configure(app =>
{
Output("webHostBuilder.Configure - Called");
})
.UseStartup<Startup>();
Output("Build WebHost");
var webHost = webHostBuilder.Build();
return webHost;
}
public static void Output(string message)
{
Console.WriteLine($"[{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")}] {message}");
}
}
}
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace MyWebsite
{
public class Startup
{
public Startup()
{
Program.Output("Startup Constructor - Called");
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
Program.Output("Startup.ConfigureServices - Called");
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IApplicationLifetime appLifetime)
{
appLifetime.ApplicationStarted.Register(() =>
{
Program.Output("ApplicationLifetime - Started");
});
appLifetime.ApplicationStopping.Register(() =>
{
Program.Output("ApplicationLifetime - Stopping");
});
appLifetime.ApplicationStopped.Register(() =>
{
Thread.Sleep(5 * 1000);
Program.Output("ApplicationLifetime - Stopped");
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
// For trigger stop WebHost
var thread = new Thread(new ThreadStart(() =>
{
Thread.Sleep(5 * 1000);
Program.Output("Trigger stop WebHost");
appLifetime.StopApplication();
}));
thread.Start();
Program.Output("Startup.Configure - Called");
}
}
}
輸出內容少了webHostBuilder.Configure - Called,由於Configure
只能有一個,後註冊的Configure
會把以前註冊的覆蓋掉。
程序執行流程以下:
Application startup in ASP.NET Core
Hosting in ASP.NET Core
老司機發車啦:https://github.com/SnailDev/SnailDev.NETCore2Learning