【ASP.NET Core】執行原理(1):建立WebHost

Never、C發表於2017-12-05

本系列將分析ASP.NET Core執行原理

本節將分析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)
{
    host.RunAsync(cts.Token, "Application started. Press Ctrl+C to shut down.").GetAwaiter().GetResult();
}

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

相關文章