1. 程式人生 > >ASP.NET Core 2 學習筆記(二)生命周期

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

RF Go 使用 HR runt block top 最大的 env

原文:ASP.NET Core 2 學習筆記(二)生命周期

要了解程序的運行原理,就要先知道程序的進入點及生命周期。以往ASP.NET MVC的啟動方式,是繼承 HttpApplication 作為網站開始的進入點,而ASP.NET Core 改變了網站的啟動方式,變得比較像是 Console Application。

本篇將介紹ASP.NET Core 的程序生命周期 (Application Lifetime) 及捕捉 Application 停止啟動事件。

程序進入點

.NET Core 把 Web 及 Console 項目都處理成一樣的啟動方式,默認以 Program.csProgram.Main

作為程序入口,再從程序入口把 ASP.NET Core 網站實例化。個人覺得比ASP.NET MVC 繼承 HttpApplication 的方式簡潔許多。

通過 .NET Core CLI 創建的 Program.cs 內容大致如下:
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;

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 的網站實例。

  • 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 內容大致如下:

Startup.cs

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 設置,變成啟動的前置準備。如下:

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)
        {
            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();
    }
}

ConfigureServicesConfigure 都改到 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

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