【ASP.NET Core】運行原理之創建WebHost

来源:http://www.cnblogs.com/neverc/archive/2017/12/05/7988226.html
-Advertisement-
Play Games

本節將分析 代碼。 源代碼參考.NET Core 2.0.0 "WebHostBuilder" "WebHost" "Kestrel" 問題概要 1. Hosting中有哪2個ServiceProvider,各自如何創建,以及有哪些ServiceCollection。 1. 什麼時候執行Startu ...


本節將分析WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().Build();代碼。

源代碼參考.NET Core 2.0.0

問題概要

  1. Hosting中有哪2個ServiceProvider,各自如何創建,以及有哪些ServiceCollection。
  2. 什麼時候執行Startup的ConfigureServices 和 Configure方法
  3. 什麼時候註冊和使用的Server
  4. 手工模擬一個DefaultWebHost環境

WebHost.CreateDefaultBuilder(args)

該方法為WebHost類的靜態方法,內部創建1個WebHostBuilder。

  1. 參數args將作為配置項
  2. 添加了Kestrel、Configuration、Logging、IISIntegration中間件,同時配置ContentRoot和DefaultServiceProvider
public static IWebHostBuilder CreateDefaultBuilder(string[] args)
{
    var builder = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var env = hostingContext.HostingEnvironment;

            config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

            if (env.IsDevelopment())
            {
                var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                if (appAssembly != null)
                {
                    config.AddUserSecrets(appAssembly, optional: true);
                }
            }

            config.AddEnvironmentVariables();

            if (args != null)
            {
                config.AddCommandLine(args);
            }
        })
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
            logging.AddDebug();
        })
        .UseIISIntegration()
        .UseDefaultServiceProvider((context, options) =>
        {
            options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
        });
    return builder;
}

UseKestrel

UseKestrel()方法中,註冊了3個服務到List<Action<WebHostBuilderContext, IServiceCollection>>欄位上。(以供後續註冊)

public static IWebHostBuilder UseKestrel(this IWebHostBuilder hostBuilder)
{
    return hostBuilder.ConfigureServices((Action<IServiceCollection>) (services =>
    {
        services.AddSingleton<ITransportFactory, LibuvTransportFactory>();
        services.AddTransient<IConfigureOptions<KestrelServerOptions>, KestrelServerOptionsSetup>();
        services.AddSingleton<IServer, KestrelServer>();
    }));
}

public IWebHostBuilder ConfigureServices(Action<WebHostBuilderContext, IServiceCollection> configureServices)
{
    this._configureServicesDelegates.Add((_, services) => configureServices(services));
    return (IWebHostBuilder) this;
}

UseContentRoot

UseContentRoot方法則是添加到IConfiguration欄位上,這個欄位在構造函數初始化
this._config = (IConfiguration) new ConfigurationBuilder().AddEnvironmentVariables("ASPNETCORE_").Build();

public static IWebHostBuilder UseContentRoot(this IWebHostBuilder hostBuilder, string contentRoot)
{
    if (contentRoot == null)
    throw new ArgumentNullException(nameof (contentRoot));
    return hostBuilder.UseSetting(WebHostDefaults.ContentRootKey, contentRoot);
}

public IWebHostBuilder UseSetting(string key, string value)
{
    this._config[key] = value;
    return (IWebHostBuilder) this;
}

ConfigureAppConfiguration

ConfigureAppConfiguration方法是添加到List<Action<WebHostBuilderContext, IConfigurationBuilder>>欄位上
在外部添加了
AddJsonFile("appsettings.json")AddJsonFile(string.Format("appsettings.{0}.json", (object) hostingEnvironment.EnvironmentName))
AddEnvironmentVariables()
AddCommandLine(args)

public IWebHostBuilder ConfigureAppConfiguration(Action<WebHostBuilderContext, IConfigurationBuilder> configureDelegate)
{
    this._configureAppConfigurationBuilderDelegates.Add(configureDelegate);
    return (IWebHostBuilder) this;
}

ConfigureLogging

ConfigureLogging註冊Log到ServiceCollection上
在外部添加了3個ILoggerProvider
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();

public static IWebHostBuilder ConfigureLogging(this IWebHostBuilder hostBuilder, Action<WebHostBuilderContext, ILoggingBuilder> configureLogging)
{
    return hostBuilder.ConfigureServices((context, services) => services.AddLogging(builder => configureLogging(context, builder));
}

public IWebHostBuilder ConfigureServices(Action<WebHostBuilderContext, IServiceCollection> configureServices)
{
    this._configureServicesDelegates.Add(configureServices);
    return (IWebHostBuilder) this;
}

UseDefaultServiceProvider

UseDefaultServiceProvider配置和替換服務

var options = new ServiceProviderOptions { ValidateScopes = context.HostingEnvironment.IsDevelopment()};
services.Replace(ServiceDescriptor.Singleton<IServiceProviderFactory<IServiceCollection>>((IServiceProviderFactory<IServiceCollection>) new DefaultServiceProviderFactory(options)));

UseStartup

UseStartup相當於註冊了一個IStartup服務。

public static IWebHostBuilder UseStartup(this IWebHostBuilder hostBuilder, Type startupType)
{
    string name = startupType.GetTypeInfo().Assembly.GetName().Name;
    return hostBuilder.UseSetting(WebHostDefaults.ApplicationKey, name).ConfigureServices((Action<IServiceCollection>) (services =>
    {
    if (typeof (IStartup).GetTypeInfo().IsAssignableFrom(startupType.GetTypeInfo()))
        ServiceCollectionServiceExtensions.AddSingleton(services, typeof (IStartup), startupType);
    else
        ServiceCollectionServiceExtensions.AddSingleton(services, typeof (IStartup), (Func<IServiceProvider, object>) (sp =>
        {
        IHostingEnvironment requiredService = sp.GetRequiredService<IHostingEnvironment>();
        return (object) new ConventionBasedStartup(StartupLoader.LoadMethods(sp, startupType, requiredService.EnvironmentName));
        }));
    }));
}

根據Startup是否繼承IStartup,來決定註冊的方式。未繼承的時候,會使用ConventionBasedStartup來封裝自定義的Startup。

Build

Build方法是WebHostBuilder最終的目的,將構造一個WebHost返回。

同時初始化WebHost對象,WebHostBuilder.Build代碼:

public IWebHost Build()
{
    var hostingServices = BuildCommonServices(out var hostingStartupErrors);
    var applicationServices = hostingServices.Clone();
    var hostingServiceProvider = hostingServices.BuildServiceProvider();

    AddApplicationServices(applicationServices, hostingServiceProvider);

    var host = new WebHost(
        applicationServices,
        hostingServiceProvider,
        _options,
        _config,
        hostingStartupErrors);

    host.Initialize();

    return host;
}

在Build方法中,BuildCommonServices最為重要,將構造第一個ServiceCollection。這裡我們稱為hostingServices
將包含hostEnv、Config、ApplicationBuilder、Logging、StartupFilter、Startup、Server。參考BuildCommonServices

private IServiceCollection BuildCommonServices(out AggregateException hostingStartupErrors)
{
    if (!this._options.PreventHostingStartup)
    {
        foreach (string hostingStartupAssembly in (IEnumerable<string>) this._options.HostingStartupAssemblies)
        {
            foreach (HostingStartupAttribute customAttribute in Assembly.Load(new AssemblyName(hostingStartupAssembly)).GetCustomAttributes<HostingStartupAttribute>())
                ((IHostingStartup) Activator.CreateInstance(customAttribute.HostingStartupType)).Configure((IWebHostBuilder) this);
        }
    }
    ServiceCollection services = new ServiceCollection();
    // hostEnv
    _hostingEnvironment.Initialize(this._options.ApplicationName, this.ResolveContentRootPath(this._options.ContentRootPath, AppContext.BaseDirectory), this._options);
    services.AddSingleton<IHostingEnvironment>(this._hostingEnvironment);
    // config
    IConfigurationBuilder configurationBuilder = new ConfigurationBuilder().SetBasePath(this._hostingEnvironment.ContentRootPath).AddInMemoryCollection(this._config.AsEnumerable());
    foreach (Action<WebHostBuilderContext, IConfigurationBuilder> configurationBuilderDelegate in this._configureAppConfigurationBuilderDelegates)
        configurationBuilderDelegate(this._context, configurationBuilder);
    IConfigurationRoot configurationRoot = configurationBuilder.Build();
    services.AddSingleton<IConfiguration>((IConfiguration) configurationRoot);
    services.AddOptions();
    // application
    services.AddTransient<IApplicationBuilderFactory, ApplicationBuilderFactory>();
    services.AddTransient<IHttpContextFactory, HttpContextFactory>();
    services.AddScoped<IMiddlewareFactory, MiddlewareFactory>();
    // log
    services.AddLogging();
    services.AddTransient<IStartupFilter, AutoRequestServicesStartupFilter>();
    services.AddTransient<IServiceProviderFactory<IServiceCollection>, DefaultServiceProviderFactory>();
    // 配置的StartupType
    if (!string.IsNullOrEmpty(this._options.StartupAssembly))
    {
        Type startupType = StartupLoader.FindStartupType(this._options.StartupAssembly, this._hostingEnvironment.EnvironmentName);
        if (typeof (IStartup).GetTypeInfo().IsAssignableFrom(startupType.GetTypeInfo()))
            ServiceCollectionServiceExtensions.AddSingleton(services, typeof (IStartup), startupType);
        else
            ServiceCollectionServiceExtensions.AddSingleton(services, typeof (IStartup), new ConventionBasedStartup(StartupLoader.LoadMethods(startupType)));
    }
    // UseStartup、UseKestrel、ConfigureLogging
    foreach (Action<WebHostBuilderContext, IServiceCollection> servicesDelegate in this._configureServicesDelegates)
        servicesDelegate(this._context, (IServiceCollection) services);
    return (IServiceCollection) services;
}

hostingServices 創建完成後,會馬上拷貝一份applicationServices提供給WebHost使用,同時創建第一個ServiceProvider hostingServiceProvider

host.Initialize()該方法則是初始化WebHost

  1. 生成第二個ServiceProvider _applicationServices(微軟的內部欄位命名,感覺不太規範);
  2. 初始化Server,讀取綁定的地址。
  3. 創建Application管道,生成RequestDelegate
public void Initialize()
{
    _startup = _hostingServiceProvider.GetService<IStartup>();
    _applicationServices = _startup.ConfigureServices(_applicationServiceCollection);
    EnsureServer();
    var builderFactory = _applicationServices.GetRequiredService<IApplicationBuilderFactory>();
    var builder = builderFactory.CreateBuilder(Server.Features);
    builder.ApplicationServices = _applicationServices;

    var startupFilters = _applicationServices.GetService<IEnumerable<IStartupFilter>>();
    Action<IApplicationBuilder> configure = _startup.Configure;
    foreach (var filter in startupFilters.Reverse())
    {
        configure = filter.Configure(configure);
    }
    configure(builder);

    this._application = builder.Build();    // RequestDelegate
}

WebHost.Run

創建完 WebHost 之後,便調用它的 Run 方法,而 Run 方法會去調用 WebHost 的 StartAsync 方法

  1. 調用Server.Start,將Initialize方法創建的Application管道傳入以供處理消息
  2. 執行HostedServiceExecutor.StartAsync方法
public static void Run(this IWebHost host)
{
    await host.RunAsync(cts.Token, "Application started. Press Ctrl+C to shut down.");
}

private static async Task RunAsync(this IWebHost host, CancellationToken token, string shutdownMessage)
{
    await host.StartAsync(token);
    var hostingEnvironment = host.Services.GetService<IHostingEnvironment>();
    Console.WriteLine($"Hosting environment: {hostingEnvironment.EnvironmentName}");
    Console.WriteLine($"Content root path: {hostingEnvironment.ContentRootPath}");
    var serverAddresses = host.ServerFeatures.Get<IServerAddressesFeature>()?.Addresses;

    if (serverAddresses != null)
        foreach (var address in serverAddresses)
            Console.WriteLine($"Now listening on: {address}");

    if (!string.IsNullOrEmpty(shutdownMessage))
        Console.WriteLine(shutdownMessage);
}

public virtual async Task StartAsync(CancellationToken cancellationToken = default (CancellationToken))
{
    Initialize();
    _applicationLifetime = _applicationServices.GetRequiredService<IApplicationLifetime>() as ApplicationLifetime;
    _hostedServiceExecutor = _applicationServices.GetRequiredService<HostedServiceExecutor>();
    var httpContextFactory = _applicationServices.GetRequiredService<IHttpContextFactory>();
    var hostingApp = new HostingApplication(_application, _logger, diagnosticSource, httpContextFactory);
    await Server.StartAsync(hostingApp, cancellationToken).ConfigureAwait(false);

    _applicationLifetime?.NotifyStarted();
    await _hostedServiceExecutor.StartAsync(cancellationToken).ConfigureAwait(false);
}

問題解答

  1. hostingServices(WebHostBuilder) 和 _applicationServices(WebHost)。區別是_applicationServices中比hostingServices多處Startup方法註冊的服務。
  2. 都是WebHost中執行的。ConfigureServices在_applicationServices生成前,Configure在_applicationServices生成後。
  3. 最初的註冊在WebHostBuilder的UseKestrel,使用在WebHost的Run方法

手工模擬一個DefaultWebHost環境

new WebHostBuilder()
    .UseKestrel()                                       // 使用Kestrel伺服器
    .UseContentRoot(Directory.GetCurrentDirectory())    // 配置根目錄 會在ConfigurationBuilder、 IHostingEnvironment(後續其他中間件) 和 WebHostOptions(WebHost)用到。
    .ConfigureAppConfiguration((context, builder) => builder.AddJsonFile("appsetting.json", true, true))    // 添加配置源
    .ConfigureLogging(builder => builder.AddConsole())  // 添加日誌適配器
    .UseStartup<Startup>()                              // 選擇Startup
    .Build().Run();                                     // 生成WebHost 並 啟動

本文鏈接:http://neverc.cnblogs.com/p/7988226.html


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • inspect模塊用於收集python對象的信息,可以獲取類或函數的參數的信息,源碼,解析堆棧,對對象進行類型檢查等等,有幾個好用的方法: getargspec(func) 返回一個命名元組ArgSpect(args, varargs, keywords, defaults),args是函數位置參數 ...
  • python數據轉換json 將json轉換為pathon數據 repr 和 eval用法 json讀取和寫入 總結: 數據轉換 第一步: 引入json包: import json 第二步: 使用 json.dumps(pythonObj) 把python數據轉換json數據 第三步: 使用json ...
  • 許久沒更新博客了! spring還有一章aop(面向切麵),我就沒講述了,你們可以去看下代理模式。 那麼我們開始整合:struts2 2.3.4 ,hibernate 5.2.10 ,spring 4.3.10 ,一直以來用到的xml式,那麼整合也不例外,就是有些麻煩。另外註解式想瞭解請留言(雖然s ...
  • 模擬用戶登錄 ...
  • 整合SSH時,遇到了org.springframework.beans.factory.BeanCreationException錯誤 ...
  • 返回總目錄 本小節目錄 Pull Up Field(欄位上移) Pull Up Method(函數上移) Pull Up Constructor Body(構造函數本體上移) 1Pull Up Field(欄位上移) 概要 兩個子類擁有相同的欄位。將該欄位移至基類。 動機 如果各個子類是分別開發的, ...
  • Nginx在WebApi集群,除了OAUTH身份驗證外,針對移動端的手機、平板電腦等,還經常使用Token令牌驗證,通過伺服器授權發出有效期的Token,客戶端通過此Token在當前有效期內,進行訪問獲取信息數據。Token驗證在很多方面都廣泛應用,舉一個實際應用場景:A客戶想通過接收郵件或者簡訊網... ...
  • 1.名詞解釋 (1)協變:父類的對象用子類代替 (2)抗變:子類的對象用父類代替 如方法的參數是協變的,而返回值是抗變的。 2.泛型介面的協變與抗變 (1)協變:IDemo<out T> 》IDemo<out ParentT> 泛型類型T只能作為IDemo中方法或屬性的返回值 (2)抗變:IDemo ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...