通过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)
本文重点解说下Host.CreateDefaultBuilder(args)的执行过程,Microsoft.Extensions.Hosting.Host是一个动态类,蕴含2个办法:
public static IHostBuilder CreateDefaultBuilder() =>CreateDefaultBuilder(args: null);public static IHostBuilder CreateDefaultBuilder(string[] args);
下面的办法最终调用的还是上面的办法,上面的办法次要包含几个局部:主机配置ConfigureHostConfiguration,应用程序配置ConfigureAppConfiguration,日志配置ConfigureLogging,依赖注入配置UseDefaultServiceProvider。
二.主机配置ConfigureHostConfiguration
主机配置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
应用程序配置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.程序运行的主机环境
hostingContext.HostingEnvironment示意运行程序的主机环境,比方开发环境或者生产环境。IHostEnvironment接口的数据结构为:
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
日志配置ConfigureLogging相干源码如下:
.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();
阐明:这一部分具体的日志剖析能够参考[6]。
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相干源码如下:
.UseDefaultServiceProvider((context, options) =>{ bool isDevelopment = context.HostingEnvironment.IsDevelopment(); options.ValidateScopes = isDevelopment; options.ValidateOnBuild = isDevelopment;});
UseDefaultServiceProvider次要是设置默认的依赖注入容器。
参考文献:
[1].NET Source Browser:https://source.dot.net/
[2]Safe storage of app secrets in development in ASP.NET Core:https://docs.microsoft.com/en...
[3]意识ASP.NET Core/Host及其配置解析:https://zhuanlan.zhihu.com/p/...
[4]源码解析.Net中Host主机的构建过程:https://www.cnblogs.com/snail...
[5].NET Core通用Host源码剖析:https://www.cnblogs.com/yingb...
[6]基于.NetCore3.1系列--日志记录之日志配置揭秘:https://www.cnblogs.com/i3yua...
[7]基于.NetCore3.1系列--日志记录之日志外围因素揭秘:https://www.cnblogs.com/i3yua...
[8].NET5中Host.CreateDefaultBuilder(args)详解:https://blog.csdn.net/qbc1234...
[9]ASP.NET启动和运行机制:https://www.jianshu.com/p/59c...
[10]ASP.Net Core解读通用主机和托管服务:https://www.cnblogs.com/qtige...
本文由mdnice多平台公布