ASP.NET Core 5.0中的Host.CreateDefaultBuilder执行过程分析
发布时间:2023-03-02 13:07:52 所属栏目:Asp教程 来源:
导读:通过Rider调试的方式看了下ASP.NET Core 5.0的Web API默认项目,重点关注Host.CreateDefaultBuilder(args)中的执行过程,主要包括主机配置、应用程序配置、日志配置和依赖注入配置这4个部分。由于水平和篇幅有限,先
|
通过Rider调试的方式看了下ASP.NET Core 5.0的Web API默认项目,重点关注Host.CreateDefaultBuilder(args)中的执行过程,主要包括主机配置、应用程序配置、日志配置和依赖注入配置这4个部分。由于水平和篇幅有限,先整体理解、建立框架,后面再逐步细化,对每个配置部分再详细拆解 一.创建默认主机Host.CreateDefaultBuilder 1.创建主机构建器CreateHostBuilder(args) 基于ASP.NET Core 5.0构建的Web API项目的Program.cs文件大家应该都很熟悉: public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } 2.创建默认构建器Host.CreateDefaultBuilder(args) public static IHostBuilder CreateDefaultBuilder() =>CreateDefaultBuilder(args: null); public static IHostBuilder CreateDefaultBuilder(string[] args); 上面的方法最终调用的还是下面的方法,下面的方法主要包括几个部分:主机配置ConfigureHostConfiguration,应用程序配置ConfigureAppConfiguration,日志配置ConfigureLogging,依赖注入配置UseDefaultServiceProvider。 二.主机配置ConfigureHostConfiguration builder.UseContentRoot(Directory.GetCurrentDirectory()); builder.ConfigureHostConfiguration(config => { config.AddEnvironmentVariables(prefix: "DOTNET_"); if (args != null) { config.AddCommandLine(args); } }); 1.内存配置源 Directory.GetCurrentDirectory()当前目录指的就是D:\SoftwareProject\C#Program\WebApplication3\WebApplication3。 2.环境变量配置源 config.AddEnvironmentVariables(prefix: "DOTNET_")添加了前缀为DOTNET_的环境变量。 3.命令行配置源 最开始认为参数args为null,经过调试发现args的值string[0],并且args != null,所以会有命令行配置源CommandLineConfigurationSource。 三.应用程序配置ConfigureAppConfiguration builder.ConfigureAppConfiguration((hostingContext, config) => { IHostEnvironment env = hostingContext.HostingEnvironment; bool reloadOnChange = hostingContext.Configuration.GetValue("hostBuilder:reloadConfigOnChange", defaultValue: true); config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: reloadOnChange).AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: reloadOnChange); if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName)) { var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName)); if (appAssembly != null) { config.AddUserSecrets(appAssembly, optional: true); } } config.AddEnvironmentVariables(); if (args != null) { config.AddCommandLine(args); } }) 1.程序运行的主机环境 public interface IHostEnvironment { // Development string EnvironmentName { get; set; } // WebApplication3 string ApplicationName { get; set; } // D:\SoftwareProject\C#Program\WebApplication3\WebApplication3 string ContentRootPath { get; set; } // PhysicalFileProvider IFileProvider ContentRootFileProvider { get; set; } } 2.加载json配置文件 接下来就是通过AddJsonFile()来添加配置文件了,如下所示: (1)Path(string):json文件的相对路径位置。 (2)Optional(bool):指定文件是否是必须的,如果为false,那么如果找不到文件就会抛出文件找不到异常。 (3)ReloadOnchange(bool):如果为true,那么当改变配置文件,应用程序也会随之更改而无需重启。 在该项目中总共有2个配置文件,分别是appsettings.json和appsettings.Development.json。 3.添加用户秘钥配置源 config.AddUserSecrets(appAssembly, optional: true)主要是在开发的过程中,用来保护配置文件中的敏感数据的,比如密码等。因为平时在开发中很少使用,所以在此不做深入讨论,如果感兴趣可参考[3]。 四.日志配置 .ConfigureLogging((hostingContext, logging) => { bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); if (isWindows) { // Default the EventLogLoggerProvider to warning or above logging.AddFilter<EventLogLoggerProvider>(level => level >= LogLevel.Warning); } logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); logging.AddDebug(); logging.AddEventSourceLogger(); if (isWindows) { // Add the EventLogLoggerProvider on windows machines logging.AddEventLog(); } logging.Configure(options => { options.ActivityTrackingOptions = ActivityTrackingOptions.SpanId | ActivityTrackingOptions.TraceId | ActivityTrackingOptions.ParentId; }); }) 1.Windows日志级别 从上述代码中可以看到是LogLevel.Warning及以上。 2.日志的配置 ILoggerProvider不同的实现方式有:ConsoleLoggerProvider,DebugLoggerProvider,EventSourceLoggerProvider,EventLogLoggerProvider,TraceSourceLoggerProvider,自定义。 logging.AddConsole(); //将日志输出到控制台 logging.AddDebug(); //将日志输出到调试窗口 logging.AddEventSourceLogger(); logging.AddEventLog(); 3.ActivityTrackingOptions public enum ActivityTrackingOptions { None = 0, //No traces will be included in the log SpanId = 1, //The record will contain the Span identifier TraceId = 2, //The record will contain the tracking identifier ParentId = 4, //The record will contain the parent identifier TraceState = 8, //The record will contain the tracking status TraceFlags = 16, //The log will contain trace flags } 在最新的.NET 7 Preview6中又增加了Tags(32)和Baggage(64)。 五.依赖注入配置UseDefaultServiceProvider .UseDefaultServiceProvider((context, options) => { bool isDevelopment = context.HostingEnvironment.IsDevelopment(); options.ValidateScopes = isDevelopment; options.ValidateOnBuild = isDevelopment; }); UseDefaultServiceProvider主要是设置默认的依赖注入容器。 (编辑:驾考网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
