In .NET 10, how do Host.CreateApplicationBuilder and Host.CreateDefaultBuilder differ, and which defaults do both apply?
answer
- properties versus callbacks
- ConfigurationManager readable before Build
- same default sources and providers
- Development turns on two validations
- HostApplicationBuilderSettings for host settings
basics
~20 sCreateApplicationBuilder returns a HostApplicationBuilder whose Configuration, Services and Logging you change directly; CreateDefaultBuilder returns an IHostBuilder that queues callbacks until Build. Both apply the same defaults for content root, configuration, logging, DI validation and lifetime.
solid answer
~40 s`Host.CreateApplicationBuilder` returns a `HostApplicationBuilder` with properties: `Configuration` is a `ConfigurationManager`, so values from `appsettings.json` are readable before `Build()`, and you register services on `builder.Services` in straight-line code. `Host.CreateDefaultBuilder` returns an `IHostBuilder` whose `ConfigureHostConfiguration`, `ConfigureAppConfiguration` and `ConfigureServices` callbacks are queued and run inside `Build()`, so configuration is only reachable through `HostBuilderContext`. Both apply the same defaults: content root from the current directory (the app folder instead when that is system32 on Windows), `DOTNET_` environment variables and command-line args as host configuration, `appsettings.json`, `appsettings.{Environment}.json`, user secrets in Development, environment variables and args as app configuration, Console, Debug and EventSource logging (plus EventLog on Windows), `ValidateScopes` and `ValidateOnBuild` in Development, and `ConsoleLifetime`. New code uses the application builder; the callback builder remains for code written against `IHostBuilder`.
code
csharp · 14 linesusing Microsoft.Extensions.Configuration;
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
// ConfigurationManager: sources are readable before Build()
Console.WriteLine($"Environment: {builder.Environment.EnvironmentName}");
Console.WriteLine($"Content root: {builder.Environment.ContentRootPath}");
foreach (IConfigurationProvider provider in ((IConfigurationRoot)builder.Configuration).Providers)
Console.WriteLine($" {provider}");
using IHost host = builder.Build();
Console.WriteLine($"IHostLifetime: {host.Services.GetRequiredService<IHostLifetime>().GetType().Name}");
Console.WriteLine("Logger providers: " + string.Join(", ",
host.Services.GetServices<ILoggerProvider>().Select(p => p.GetType().Name)));go deeper
Recall that both builders exist, that the worker template uses Host.CreateApplicationBuilder, and that both read appsettings.json and environment variables.
Contrast properties with deferred callbacks, list the default sources in order, and explain that ValidateScopes and ValidateOnBuild switch on only in Development.
Know where defaults hide surprises: the content root follows the current directory, settings must be fixed at construction, and DisableDefaults removes more than logging.
Standardise one builder style across a team's tools and workers so configuration, logging and validation behave identically everywhere.
## Two builders, one host The **generic host** (`IHost`) bundles configuration, logging, dependency injection and lifetime management for any .NET app. Two static factory methods on `Microsoft.Extensions.Hosting.Host` produce a builder for it: - `Host.CreateDefaultBuilder(args)` returns an **`IHostBuilder`** (a `HostBuilder` with `ConfigureDefaults` applied). It is the older, callback-based style. - `Host.CreateApplicationBuilder(args)` returns a **`HostApplicationBuilder`**, a sealed class with mutable properties. The worker template uses it, and it is what the docs recommend for new code. Both end in a `Build()` that may be called only once (a second call throws `InvalidOperationException` with "Build can only be called once."), and both build the same internal host type. ## Properties versus deferred callbacks | Aspect | `HostApplicationBuilder` | `IHostBuilder` | |---|---|---| | Configuration | `builder.Configuration` is a `ConfigurationManager`; added sources are readable at once | `ConfigureAppConfiguration((ctx, cfg) => …)` callbacks run inside `Build()` | | Services | `builder.Services` is an `IServiceCollection` you add to directly | `ConfigureServices((ctx, services) => …)` callbacks | | Logging | `builder.Logging` | `ConfigureLogging(…)` callback | | Reading config to decide registrations | ordinary `if` on `builder.Configuration[...]` | inside a callback via `ctx.Configuration` | | Environment, content root, app name | fixed at construction through `HostApplicationBuilderSettings` | `ConfigureHostConfiguration` or `UseEnvironment`/`UseContentRoot` | | Hosting extensions | `IServiceCollection` forms such as `AddWindowsService()`, `AddSystemd()` | `IHostBuilder` forms such as `UseWindowsService()`, `UseSystemd()` | After `HostApplicationBuilder.Build()` the service collection is made read-only, so a registration added later throws instead of being silently ignored. ## The defaults both builders apply The source of `Microsoft.Extensions.Hosting` 10.0.12 runs the same helpers for both builders: 1. **Content root**: the current directory, except on Windows when the current directory is `Environment.SystemDirectory` (the case for Windows Services); then the content root falls back to `AppContext.BaseDirectory`. 2. **Host configuration**: environment variables prefixed `DOTNET_` (so `DOTNET_ENVIRONMENT` sets the environment) and the command line, when args are passed. 3. **App configuration**, in order: `appsettings.json`, `appsettings.{Environment}.json`, `{ApplicationName}.settings.json` and its environment variant, user secrets when the environment is `Development` (found through the entry assembly), environment variables, then the command line. JSON files are optional and reload on change by default. 4. **Logging**: Console, Debug and EventSource providers, plus EventLog on Windows with a default filter of `Warning` and above; the `Logging` section of configuration drives levels. 5. **DI validation**: when the environment is `Development`, the default service provider is built with both `ValidateScopes` and `ValidateOnBuild` set. What those checks catch is covered with DI lifetimes. 6. **Lifetime**: `ConsoleLifetime` is registered as `IHostLifetime`, and `HostOptions` reads keys such as `shutdownTimeoutSeconds` and `servicesStartConcurrently` from configuration. When nothing sets an environment name, it is `Production`. ## Changing host settings with `HostApplicationBuilder` Because the application builder loads configuration in its constructor, the environment, application name and content root must be known before that happens. Pass them in **`HostApplicationBuilderSettings`**: - `EnvironmentName`, `ContentRootPath` and `ApplicationName` override every other source; `Args` supplies the command line. - `DisableDefaults = true` skips the default content root, configuration sources, logging providers and Development validation; command-line args you pass are still added. - `Configuration` lets you hand in a pre-populated `ConfigurationManager`. - `Host.CreateEmptyApplicationBuilder(settings)` starts without the default configuration sources, logging providers or validation, for apps that want to choose each one; the core host services are still registered. ## Which one to use - Use **`CreateApplicationBuilder`** for new console tools and workers: straight-line code, configuration readable at any point, and the same shape as `WebApplicationBuilder`. - Keep **`CreateDefaultBuilder`** where existing code, tests or a library expose extension methods only on `IHostBuilder`, or during a gradual migration. - Do not assume a difference in defaults: both read the same files and register the same providers, so moving between them changes code style, not behaviour. ## Moving a worker from `CreateDefaultBuilder` to `CreateApplicationBuilder` 1. Replace `Host.CreateDefaultBuilder(args)` with `Host.CreateApplicationBuilder(args)` and keep the returned `builder`. 2. Move the body of each `ConfigureServices((ctx, services) => …)` to statements on `builder.Services`, replacing `ctx.Configuration` with `builder.Configuration` and `ctx.HostingEnvironment` with `builder.Environment`. 3. Move `ConfigureAppConfiguration` calls to `builder.Configuration.Add…` statements, and `ConfigureLogging` to `builder.Logging`. 4. Replace `UseEnvironment`, `UseContentRoot` and other host-configuration calls with `HostApplicationBuilderSettings`, because they must be known before the defaults load. 5. Swap `IHostBuilder` extensions for their `IServiceCollection` forms (`UseWindowsService()` becomes `builder.Services.AddWindowsService()`), then `builder.Build().Run()`. Run the worker once in each environment after the move and compare the start-up log lines for environment and content root; they should not change.
- How do you run a HostApplicationBuilder-based worker in the Staging environment with a fixed content root?Set `DOTNET_ENVIRONMENT=Staging` or pass `--environment Staging`, or build with `Host.CreateApplicationBuilder(new HostApplicationBuilderSettings { Args = args, EnvironmentName = "Staging", ContentRootPath = AppContext.BaseDirectory })`. The settings must be given at construction, because the builder loads `appsettings.{Environment}.json` from the content root inside its constructor.
- What does `HostApplicationBuilderSettings.DisableDefaults = true` still give you?The host still registers `IHostEnvironment`, `IHostApplicationLifetime`, `ConsoleLifetime` and `HostOptions`, and adds the command-line args you passed. It drops the current-directory content root, `DOTNET_` variables, the JSON, user-secrets and environment-variable sources, the default logging providers and the Development validation, so you add each one you need.
- CreateDefaultBuilder loads appsettings.json but CreateApplicationBuilder does not.
- HostApplicationBuilder exposes configuration only after Build() has run.
- The default content root is always the folder that holds the executable.
- The default host builders validate scopes in every environment, not only Development.
- Host.CreateApplicationBuilder registers the EventLog provider on Linux as well.
Assumes .NET 10 (Microsoft.Extensions.Hosting 10.0.12); the default configuration sources below were printed from that version, including the {ApplicationName}.settings.json files.