Skip to content

NET_Core_Hosting

Denis Zykov edited this page Oct 25, 2026 · 4 revisions

You can run your command line application within the .NET Generic Host. For this you need a Nuget package:

Install-Package deniszykov.CommandLine.Hosted

And the following application startup code:

internal class Program
{
    private static async Task Main(string[] args)
    {
        await CreateHostBuilder(args).Build().RunAsync();
    }

    private static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)

        .ConfigureServices((context, services) => {
            // un-comment if you want to configure CommandLine from appsettings.json file
            // services.Configure<CommandLineConfiguration>(context.Configuration.GetSection("CommandLine"));
        })

        .ConfigureCommandLineHost(args, builder => {
            builder.Use<Program>();
        });
}

args could be omitted, then the process command line arguments are used:

.ConfigureCommandLineHost(builder => builder.Use<Program>())

Before version 2.2.1 this overload took the executable path as a verb name, so pass args explicitly on older versions.

Exit code

The verb runs as a hosted service. When it completes, its return value is written to Environment.ExitCode and the host is stopped, so await host.RunAsync() ends with the verb's exit code. If the verb throws, Environment.ExitCode is set to CommandLine.DOT_NET_EXCEPTION_EXIT_CODE.

Cancellation

The verb's CancellationToken is cancelled when the host is stopping, for example on Ctrl+C handled by the console lifetime.

Configuration

CommandLineConfiguration is taken from the host's services, either registered directly or as IOptions<CommandLineConfiguration>. This way it could be bound from appsettings.json:

.ConfigureServices((context, services) => {
    services.Configure<CommandLineConfiguration>(context.Configuration.GetSection("CommandLine"));
})
{
  "CommandLine": {
    "DefaultVerbName": "Default",
    "OutputDetailedErrors": true
  }
}

Values set with builder.Configure() inside ConfigureCommandLineHost are applied after it. See Settings reference.

Services

The host's IServiceProvider is used for service injection, verb class construction and extensibility services:

.ConfigureServices(services => {
    services.AddSingleton<IAccountService, AccountService>();
    services.AddTransient<ExceptionEventHandler>(_ => (sender, args) => { /* log args.Exception */ });
})

Clone this wiki locally