Last update:
What does WebHost’s CreateDefaultBuilder do?
ASP.NET Core 2 introduced a CreateDefaultBuilder helper method that configures a WebHost with default settings. This post shows what are these defaults.
The CreateDefaultBuilder method does the following:
- Uses Kestrel server
- Sets current directory as the Content Root
- Adds the appsettings.json and appsettings.{EnvironmentName}.json files as a config source
- Adds user secrets as a config source (only in development environment)
- Adds environment variables and commandline arguments as config sources
- Configures logging with settings from the Logging configuration section
- Adds Console and Debug loggers
- Uses IIS integration
- Adds a scope validator that checks if scoped services are not resolved from the root provider (in development only)
If you need to customize this logic, just grab the below code (that’s exactly what gets called by the framework), replace the .CreateDefaultWebHost() method call with it and make any changes you need. Remember you still need to call .UseStartup<>() and .Build().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
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(); }); if (args != null) { builder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build()); } |
Interestingly, the commandline configuration provider is added twice. This has been noticed by the team but considered not to be an issue.
Comments