HTML5技术

【ASP.NET Core】运行原理之创建WebHost - Never、C

字号+ 作者:H5之家 来源:H5之家 2017-12-06 11:22 我要评论( )

【ASP.NET Core】运行原理之创建WebHost 本节将分析WebHost.CreateDefaultBuilder(args).UseStartupStartup().Build();代码。 源代码参考.NET Core 2.0.0 问题概要WebHost.CreateDefaultBuilder(args) 该方法为WebHost类的静态方法,内部创建1个WebHostBuild

【ASP.NET Core】运行原理之创建WebHost

本节将分析WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().Build();代码。

源代码参考.NET Core 2.0.0

问题概要 WebHost.CreateDefaultBuilder(args)

该方法为WebHost类的静态方法,内部创建1个WebHostBuilder。

  • 参数args将作为配置项
  • 添加了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返回。

     

    1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

    相关文章
    • ASP.NET没有魔法——ASP.NET Identity 的“多重”身份验证代码篇 - 7m鱼

      ASP.NET没有魔法——ASP.NET Identity 的“多重”身份验证代码篇 - 7

      2017-12-01 18:01

    • Entity Framework Core 使用HiLo生成主键 - Sweet-Tang

      Entity Framework Core 使用HiLo生成主键 - Sweet-Tang

      2017-11-27 10:14

    • 使用AspectCore动态代理 - Lemon丶

      使用AspectCore动态代理 - Lemon丶

      2017-11-21 11:01

    • 极简版ASP.NET Core学习路径及教程 - 腾飞(Jesse)

      极简版ASP.NET Core学习路径及教程 - 腾飞(Jesse)

      2017-11-17 14:02

    网友点评
    o