skip to content

In a .NET console tool, how do you wire Microsoft.Extensions configuration, logging and DI without the generic host, and what do you give up?

level: middleimportance: should knowfreq 30%

answer

  1. three libraries that stand alone
  2. ConfigurationBuilder, ServiceCollection, AddLogging
  3. copy appsettings.json to output
  4. dispose the ServiceProvider
  5. no environment, no lifetime

basics

~10 s

Build an IConfiguration with ConfigurationBuilder, register services and AddLogging on a ServiceCollection, then build and dispose the ServiceProvider. You give up environments, user secrets, default providers, Development validation, hosted services and Ctrl+C handling.

solid answer

~40 s

Configuration, logging and DI are separate `Microsoft.Extensions` libraries, so a console tool can use them without a host. Build configuration with `new ConfigurationBuilder().SetBasePath(AppContext.BaseDirectory).AddJsonFile("appsettings.json").AddEnvironmentVariables().Build()`, register it and your services on a `ServiceCollection`, call `AddLogging(b => b.AddConfiguration(config.GetSection("Logging")).AddConsole())`, then `BuildServiceProvider()` inside a `using` so disposable singletons are disposed. On a plain `Microsoft.NET.Sdk` project you must also mark `appsettings.json` with `CopyToOutputDirectory`, or a required file throws `FileNotFoundException`. What you give up is everything the host adds: an environment name and `appsettings.{Environment}.json`, user secrets, the `DOTNET_` and command-line sources, default logging providers, scope validation in Development, `IHostedService` start and stop, and the console lifetime. For anything beyond a small tool, `Host.CreateApplicationBuilder` without `Run()` is usually less code.

code

csharp · 28 lines
csharp
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

IConfiguration config = new ConfigurationBuilder()
    .SetBasePath(AppContext.BaseDirectory)          // explicit: the bin folder, not the shell's directory
    .AddJsonFile("appsettings.json", optional: false)
    .AddEnvironmentVariables()
    .Build();

ServiceCollection services = new();
services.AddSingleton(config);
services.AddLogging(logging => logging
    .AddConfiguration(config.GetSection("Logging"))
    .AddConsole());
services.AddSingleton<Importer>();

using ServiceProvider provider = services.BuildServiceProvider(validateScopes: true);
return provider.GetRequiredService<Importer>().Run();

sealed class Importer(ILogger<Importer> logger, IConfiguration config)
{
    public int Run()
    {
        logger.LogInformation("Importing from {Source}", config["Import:Source"]);
        return 0;
    }
}

go deeper

for a junior

Know that ConfigurationBuilder, ServiceCollection and AddLogging work in any console app, and that appsettings.json must be copied to the output folder.

for a middle

Explain each wiring step, why the provider is disposed, and which host defaults disappear: environments, user secrets, default providers and Development validation.

for a senior

Spot the base-path difference between a hand-wired tool and a hosted one, and pick host-without-Run when a tool must share a worker's configuration rules.

for a principal

Decide whether a team's small tools hand-wire Extensions or reuse the host, so configuration lookup is the same across every executable the team ships.

## The pieces stand alone `Microsoft.Extensions` is a family of libraries that the **generic host** composes, not a framework you must buy whole: - **Configuration** (`Microsoft.Extensions.Configuration` plus provider packages such as `.Json` and `.EnvironmentVariables`) builds an `IConfiguration` from layered sources; keys use `:` for nesting, so `Import:Source` reads `{"Import": {"Source": ...}}`. - **Dependency injection** (`Microsoft.Extensions.DependencyInjection`) turns an `IServiceCollection` of registrations into a `ServiceProvider`. - **Logging** (`Microsoft.Extensions.Logging` plus providers such as `.Console`) plugs into DI through `AddLogging`. A console tool can wire these by hand. That is reasonable for a small import utility that wants the same `appsettings.json` and logging as the worker it ships beside, without a lifetime or hosted services. ## Wiring them by hand 1. **Configuration**: `new ConfigurationBuilder()`, then `SetBasePath(AppContext.BaseDirectory)`, `AddJsonFile("appsettings.json", optional: false)`, `AddEnvironmentVariables()` and `Build()`. Without `SetBasePath` the JSON provider also resolves relative names against the app's base directory, so the call mainly documents intent; the trap is passing `Directory.GetCurrentDirectory()`, which ties the tool to the shell it was launched from. 2. **Services**: `var services = new ServiceCollection();` then `services.AddSingleton(config)` and your own registrations. 3. **Logging**: `services.AddLogging(b => b.AddConfiguration(config.GetSection("Logging")).AddConsole())`. Without `AddConfiguration`, the `Logging:LogLevel` section is ignored and only the built-in minimum level applies. 4. **Provider**: `using ServiceProvider provider = services.BuildServiceProvider(validateScopes: true);` The `using` matters: disposing the provider disposes every disposable singleton it created, including the logger factory and its providers. 5. **Run**: resolve the entry service, call it, and return its result as the process exit code. ## The traps - **The file is not in `bin/`.** A plain `Microsoft.NET.Sdk` project treats `appsettings.json` as a `None` item and does not copy it. With `optional: false` you get `FileNotFoundException` ("The configuration file 'appsettings.json' was not found and is not optional."); with `optional: true` you get silent nulls. Add `<None Update="appsettings.json" CopyToOutputDirectory="PreserveNewest" />`. The Worker SDK does this for you. - **No environment.** Nothing reads `DOTNET_ENVIRONMENT` or loads `appsettings.Development.json` unless you add those sources yourself. - **No validation by default.** `BuildServiceProvider()` without arguments validates nothing; the host would have switched validation on in Development. - **No graceful stop.** Ctrl+C kills the process unless you handle `Console.CancelKeyPress` or `PosixSignalRegistration` yourself. ## What the host would have added | Concern | Hand-wired console tool | `Host.CreateApplicationBuilder` | |---|---|---| | JSON base path | `AppContext.BaseDirectory` (or what you set) | content root, the current directory by default | | `appsettings.{Environment}.json`, user secrets | add yourself | default | | `DOTNET_` variables and command-line args | add yourself | default | | Console, Debug, EventSource logging | add each provider | default | | Scope and build-time validation | opt in | on in Development | | `IHostedService` start and stop | not available | `StartAsync`/`StopAsync` | | Ctrl+C and SIGTERM handling | yours to write | `ConsoleLifetime` | ## Choosing - For a **tiny tool** that needs one JSON file and console output, hand wiring is short and has no surprises. `LoggerFactory.Create(b => b.AddConsole())` is enough when you do not need DI at all. - For a **tool that shares configuration with a worker**, use `Host.CreateApplicationBuilder(args)`, call `Build()`, resolve your service and never call `Run()`; you inherit the worker's environment handling and providers in four lines. - Either way, keep the decision explicit in code review: a hand-wired tool and a hosted worker read configuration from different base directories, which is a common source of "works on my machine" reports. ## Moving a hand-wired tool onto the host When a hand-wired tool grows, the move is mechanical: 1. Replace the `ConfigurationBuilder` block with `HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);` and delete the sources the host already adds. 2. Move registrations from the local `ServiceCollection` to `builder.Services`, and logging setup to `builder.Logging`; the `Logging` section is bound automatically. 3. Replace `BuildServiceProvider` with `using IHost host = builder.Build();` and resolve the entry service from `host.Services`. 4. Decide where the JSON files are looked up: the host uses its content root, so either start the tool from its folder or set `HostApplicationBuilderSettings.ContentRootPath = AppContext.BaseDirectory` to keep the old behaviour. Step 4 is the one that is easy to miss, because the tool keeps working from the developer's terminal and fails only when a scheduler starts it from another directory.

  • Why can the same appsettings.json load in a hand-wired console tool but not in a hosted one started from another directory?
    A `ConfigurationBuilder` resolves relative JSON names against `AppContext.BaseDirectory` unless you set a base path, while the generic host resolves them against its content root, which defaults to the current directory. Launch the hosted tool from `/` and its content root is `/`, so the optional `appsettings.json` loads nothing; set `ContentRootPath` in `HostApplicationBuilderSettings` or start it from the app folder.
  • What does disposing the `ServiceProvider` do in a console tool?
    It disposes every disposable service the provider itself created, including the logger factory and its providers. An object you registered as a ready-made instance, as in `AddSingleton(myObject)`, is not disposed, because the container did not create it; in a scratch run only the container-built singleton printed its Dispose message.

  • Configuration, logging and DI cannot be used without the generic host.
  • A plain console project copies appsettings.json to bin/ automatically.
  • BuildServiceProvider() validates scopes by default just like the host does.
  • ConfigurationBuilder reads DOTNET_ENVIRONMENT and loads the environment file on its own.
  • The ServiceProvider never needs disposing in a short-lived console app.