ASP.NET Core 2 學習筆記(二)生命週期

要了解程序的運行原理,就要先知道程序的進入點及生命週期。以往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.CreateDefaultBuilder
    經過此方法創建 WebHost Builder。WebHost Builder 是用來生成 WebHost 的對象。
    能夠在 WebHost 生成以前設置一些前置動做,當 WebHost 創建完成時,就可使用已準備好的物件等。
  • UseStartup
    設置該 Builder 生成的 WebHost 啓動後,要執行的類。
  • Build
    當前置準備都設置完成後,就能夠調用 WebHost Builder 方法實例化 WebHost,並獲得該實例。
  • Run
    啓動 WebHost。

Startup.cs

當網站啓動後,WebHost會實例化 UseStartup 設置的Startup類,而且調用如下兩個方法:網站

  • ConfigureServices
  • Configure

經過 .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!");
            });
        }
    }
}
  • ConfigureServices
    ConfigureServices 是用來將服務註冊到 DI 容器用的。這個方法可不實現,並非必要的方法。

  • Configure
    這個是必要的方法,必定要實現。但 Configure 方法的參數並不固定,參數的實例都是從 WebHost 注入進來,可依需求增減須要的參數。
    • IApplicationBuilder 是最重要的參數也是必要的參數,Request 進出的 Pipeline 都是經過 ApplicationBuilder 來設置。

對 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 註冊,網站的執行結果是同樣的。

二者之間最大的不一樣就是調用的時間點不一樣。

  • 在 WebHost Builder 註冊,是在 WebHost 實例化以前就調用。
  • 在 Startup.cs 註冊,是在 WebHost 實例化以後調用。

但 Configure 沒法使用除了 IApplicationBuilder 之外的參數。
由於在 WebHost 實例化前,本身都還沒被實例化,怎麼可能會有有對象能注入給 Configure

Application Lifetime

除了程序進入點外,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();
}
  • ApplicationStarted
    當WebHost啓動完成後,會執行的啓動完成事件。
  • ApplicationStopping
    當WebHost觸發中止時,會執行的準備中止事件。
  • ApplicationStopped
    當WebHost中止事件完成時,會執行的中止完成事件。
  • 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

相關文章
相關標籤/搜索