.net core 6 默认的配置
.net core 6已经出来很久了,默认的代码变得更加整洁,同时也出现了新的应用构建方式,这一切虽然都是慢慢发展来的,但是我们还是需要明白它背后帮我们干了哪些事情。
新文章asp.net core 管道中间件构建之深入探究已经出来了,深入了解中间件管道是如何构建的,了解各个管道的加载顺序。可以解决一些很有趣的问题
默认配置
.net core 6是默认加载的appsetting.json文件的,但是是具体在哪加载的呢,我们需要搞明白。那么就正式进入到.net core的精髓,面向反编译编程。
//program默认构建webapplicationbuilder文件,进去
var builder = WebApplication.CreateBuilder(args);
//返回的是new webapplicationbuilder, 重点是 _bootstrapHostBuilder.ConfigureDefaults(args: null);
internal WebApplicationBuilder(WebApplicationOptions options, Action<IHostBuilder>? configureDefaults = null)
{
Services = _services;
var args = options.Args;
// Run methods to configure both generic and web host defaults early to populate config from appsettings.json
// environment variables (both DOTNET_ and ASPNETCORE_ prefixed) and other possible default sources to prepopulate
// the correct defaults.
_bootstrapHostBuilder = new BootstrapHostBuilder(Services, _hostBuilder.Properties);
// Don't specify the args here since we want to apply them later so that args
// can override the defaults specified by ConfigureWebHostDefaults
_bootstrapHostBuilder.ConfigureDefaults(args: null);
// This is for testing purposes
configureDefaults?.Invoke(_bootstrapHostBuilder);
// We specify the command line here last since we skipped the one in the call to ConfigureDefaults.
// The args can contain both host and application settings so we want to make sure
// we order those configuration providers appropriately without duplicating them
if (args is { Length: > 0 })
{
_bootstrapHostBuilder.ConfigureAppConfiguration(config =>
{
config.AddCommandLine(args);
});
}
_bootstrapHostBuilder.ConfigureWebHostDefaults(webHostBuilder =>
{
// Runs inline. //使用了很多预定义中间件 比如 app.useRouting app.useEndpoints
webHostBuilder.Configure(ConfigureApplication);
// Attempt to set the application name from options
options.ApplyApplicationName(webHostBuilder);
});
// Apply the args to host configuration last since ConfigureWebHostDefaults overrides a host specific setting (the application name).
_bootstrapHostBuilder.ConfigureHostConfiguration(config =>
{
if (args is { Length: > 0 })
{
config.AddCommandLine(args);
}
// Apply the options after the args
options.ApplyHostConfiguration(config);
});
Configuration = new();
// This is chained as the first configuration source in Configuration so host config can be added later without overriding app config.
Configuration.AddConfiguration(_hostConfigurationManager);
// Collect the hosted services separately since we want those to run after the user's hosted services
_services.TrackHostedServices = true;
// This is the application configuration
var (hostContext, hostConfiguration) = _bootstrapHostBuilder.RunDefaultCallbacks(Configuration, _hostBuilder);
// Stop tracking here
_services.TrackHostedServices = false;
// Capture the host configuration values here. We capture the values so that
// changes to the host configuration have no effect on the final application. The
// host configuration is immutable at this point.
_hostConfigurationValues = new(hostConfiguration.AsEnumerable());
// Grab the WebHostBuilderContext from the property bag to use in the ConfigureWebHostBuilder
var webHostContext = (WebHostBuilderContext)hostContext.Properties[typeof(WebHostBuilderContext)];
// Grab the IWebHostEnvironment from the webHostContext. This also matches the instance in the IServiceCollection.
Environment = webHostContext.HostingEnvironment;
Logging = new LoggingBuilder(Services);
Host = new ConfigureHostBuilder(hostContext, Configuration, Services);
WebHost = new ConfigureWebHostBuilder(webHostContext, Configuration, Services);
Services.AddSingleton<IConfiguration>(_ => Configuration);
}
可以看到 configureDefaults的说明,添加各种配置,进去看看
public static IHostBuilder ConfigureDefaults(this IHostBuilder builder, string[] args)
{
builder.UseContentRoot(Directory.GetCurrentDirectory());
builder.ConfigureHostConfiguration(config =>
{
config.AddEnvironmentVariables(prefix: "DOTNET_");
if (args is { Length: > 0 })
{
config.AddCommandLine(args);
}
});
//加载各种配置 包括appsetting.json 环境变量等,这点我们要明白
builder.ConfigureAppConfiguration((hostingContext, config) =>
{
IHostEnvironment env = hostingContext.HostingEnvironment;
bool reloadOnChange = GetReloadConfigOnChangeValue(hostingContext);
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: reloadOnChange)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: reloadOnChange);
if (env.IsDevelopment() && env.ApplicationName is { Length: > 0 })
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly is not null)
{
config.AddUserSecrets(appAssembly, optional: true, reloadOnChange: reloadOnChange);
}
}
//添加环境变量,我们可以在环境变量设置我们的数据库字符串连接,这里自动加载到configuration 用的时候直接获取
config.AddEnvironmentVariables();
if (args is { Length: > 0 })
{
config.AddCommandLine(args);
}
})
.ConfigureLogging((hostingContext, logging) =>
{
bool isWindows =
#if NET6_0_OR_GREATER
OperatingSystem.IsWindows();
#else
RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
#endif
// IMPORTANT: This needs to be added *before* configuration is loaded, this lets
// the defaults be overridden by the configuration.
if (isWindows)
{
// Default the EventLogLoggerProvider to warning or above
logging.AddFilter<EventLogLoggerProvider>(level => level >= LogLevel.Warning);
}
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
#if NET6_0_OR_GREATER
if (!OperatingSystem.IsBrowser())
#endif
{
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;
});
})
.UseDefaultServiceProvider((context, options) =>
{
bool isDevelopment = context.HostingEnvironment.IsDevelopment();
options.ValidateScopes = isDevelopment;
options.ValidateOnBuild = isDevelopment;
});
return builder;
}
好了,可以明确看到它默认加载了哪些配置了 。
分类:
Asp.net Core
标签:
asp.net core
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· [翻译] 为什么 Tracebit 用 C# 开发
· 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· DeepSeek崛起:程序员“饭碗”被抢,还是职业进化新起点?
· 深度对比:PostgreSQL 和 SQL Server 在统计信息维护中的关键差异