SystemCommandLine.Extensions 2.1.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package SystemCommandLine.Extensions --version 2.1.0
                    
NuGet\Install-Package SystemCommandLine.Extensions -Version 2.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="SystemCommandLine.Extensions" Version="2.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="SystemCommandLine.Extensions" Version="2.1.0" />
                    
Directory.Packages.props
<PackageReference Include="SystemCommandLine.Extensions" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add SystemCommandLine.Extensions --version 2.1.0
                    
#r "nuget: SystemCommandLine.Extensions, 2.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package SystemCommandLine.Extensions@2.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=SystemCommandLine.Extensions&version=2.1.0
                    
Install as a Cake Addin
#tool nuget:?package=SystemCommandLine.Extensions&version=2.1.0
                    
Install as a Cake Tool

SystemCommandLine.Extensions

Build NuGet NuGet Downloads

Small, pragmatic helpers for building command-line apps with System.CommandLine and the Microsoft.Extensions hosting/DI stack.

  • Fluent builders to define options from a typed options class using expressions
  • Automatic mapping from parsed command-line values to your options (IOptions<T>)
  • DI-first wiring for commands and handlers
  • Host-friendly RootCommand setup and ParseResult lifetime integration
  • Kebab-case option names by convention (e.g., MyProperty → --my-property)

Install

dotnet add package SystemCommandLine.Extensions

Quick start

Define a command and its options using the builder API and expressions. Implement IUseCommandBuilder<TCommand> to expose a factory that the DI extensions can use. The optional ConfigureRegistration method keeps default handler and options registration with the command.

using System.CommandLine;
using System.CommandLine.Invocation;
using Microsoft.Extensions.Options;
using SystemCommandLine.Extensions;

public class Root : RootCommand, IUseCommandBuilder<Root>
{
    public static Root CommandFactory(IServiceProvider sp, ArgumentMapperRegistration mapperRegistration)
        => new();
}

public class Greet : Command, IUseCommandBuilder<Greet>
{
	public Greet(ArgumentMapperRegistration mapperRegistration)
		: base("greet", "Greets a person")
	{
		// Describe options using your options type and expressions
		this.UseCommandBuilder().WithMapping<GreetOptions>(mapperRegistration)
			.NewOption(o => o.Name).Configure(o =>
			{
				o.Description = "Name to greet";
				o.DefaultValueFactory = _ => "World";
			}).AddToCommand()
			.NewOption(o => o.Times).Configure(o =>
			{
				o.Description = "Number of times";
				o.DefaultValueFactory = _ => 1;
			}).AddToCommand();
	}

	public static Greet CommandFactory(IServiceProvider sp, ArgumentMapperRegistration mapperRegistration)
		=> new(mapperRegistration);

	public static void ConfigureRegistration(CommandRegistrationBuilder<Greet> builder)
	{
		builder.WithAsyncHandler<GreetHandler>().BindOptions<GreetOptions>();
	}
}

public class GreetOptions
{
	public string Name { get; set; } = "World";
	public int Times { get; set; }
}

public class GreetHandler(IOptions<GreetOptions> options) : AsynchronousCommandLineAction
{
    public override Task<int> InvokeAsync(ParseResult parseResult, CancellationToken cancellationToken)
    {
        for (var i = 0; i < options.Value.Times; i++)
            Console.WriteLine($"Hello, {options.Value.Name}!");
        return Task.FromResult(0);
    }
}

Wire it up with hosting and DI. The parsed values are bound into IOptions<GreetOptions>.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using System.CommandLine;
using SystemCommandLine.Extensions;

var builder = Host.CreateDefaultBuilder(args)
	.ConfigureServices(services =>
	{
		services.AddRootCommand<Root>(args)
			.AddSubCommand<Greet>();
		services.AddCommand<Greet>();
	});

using IHost host = builder.Start();
ParseResult parse = host.Services.GetRequiredService<ParseResult>();
return await parse.InvokeAsync();

See src/TestConsoleApp for a complete example, including logging integration.

Composing commands

A command can attach children inside its CommandFactory, using ordinary Command.Add or a collection initializer:

return new Root(mapperRegistration)
{
    serviceProvider.GetRequiredService<Greet>()
};

To compose commands outside their definitions, use the registration builder returned by AddRootCommand<TCommand> or AddCommand<TCommand>:

services.AddRootCommand<Root>(args)
    .AddSubCommand<Greet>();
services.AddCommand<Greet>();

In this variant, the root factory simply returns new Root(mapperRegistration); neither command needs to declare the relationship. Keep any required root options bindings in the root's ConfigureRegistration, for example builder.BindOptions<LoggerOptions>(). See src/TestConsoleApp for a complete example.

AddCommand and AddRootCommand invoke ConfigureRegistration once per registration call, before returning the builder. The hook configures services; it does not construct the command or handler. Its default interface implementation does nothing, so existing command classes can omit it and applications can still register handlers and options explicitly with the builder.

Application-level handler choices override the command's defaults:

services.AddCommand<Greet>().WithAsyncHandler<CustomGreetHandler>();

Use the command's hook for its own defaults and application startup for hierarchy composition. Both use the same registration builder; the hook's choices are applied first, followed by any application-level builder calls.

The builder offers a small set of registration operations:

Member Purpose
WithHandler<THandler>() Register and select a synchronous handler
WithAsyncHandler<THandler>() Register and select an asynchronous handler
BindOptions<TOptions>() Bind parsed values to the options type mapped by the command
AddSubCommand<TChild>() Attach a separately registered child to this command
Services Return to the original service collection

Every method returns the same command's builder. In particular, AddSubCommand does not switch to the child or register it implicitly. The child supplies its defaults when separately registered with AddCommand. Non-root commands use the same builder, so the pattern works at every level of a hierarchy. The builder exposes neither a command instance nor an arbitrary configuration callback; option definitions remain in the command class.

Register each command once and finish configuring its builder before building the service provider. Parent and child registrations can appear in either order. Commands are singletons; children are resolved and attached after the parent's factory and handler setup, before parsing. Factory-defined children are preserved, and the same child instance is not attached twice. Repeating AddSubCommand for the same child type or BindOptions for the same options type on a builder is harmless. The last WithHandler or WithAsyncHandler call selects the handler. Existing handler service registrations are respected.

Keep relationships acyclic: do not resolve a parent while constructing its child. Missing child service registrations fail when the parent is first resolved.

Use .Services to continue ordinary service registration:

services.AddCommand<Greet>()
    .WithAsyncHandler<GreetHandler>()
    .BindOptions<GreetOptions>()
    .Services
    .AddSingleton<MyService>();

Migrating registration code

This is a breaking API change: AddRootCommand and AddCommand now return CommandRegistrationBuilder<TCommand> instead of IServiceCollection. Existing consumers must migrate and recompile. Append .Services when continuing a chain of service registrations or returning the service collection.

The standalone handler/options registration helpers are replaced by builder methods:

Previous registration Builder registration
services.AddCommandWithHandler<C, H>() services.AddCommand<C>().WithHandler<H>()
services.AddCommandWithAsyncHandler<C, H>() services.AddCommand<C>().WithAsyncHandler<H>()
services.AddBoundToCommandOptions<C, O>() .BindOptions<O>() on the builder for C

Command factories, fluent option definitions, and the command-level SetHandler and SetAsyncHandler methods retain their existing contracts.

IUseCommandBuilder<TCommand> now requires where TCommand : Command, IUseCommandBuilder<TCommand> so the hook can accept the typed registration builder. Conventional command implementations already satisfy this constraint; generic wrappers that refer to the interface may need the additional constraint. ConfigureRegistration is optional and does not need to be added to existing commands.

Why use this?

System.CommandLine is powerful but low-level. This library smooths out the most common patterns in real apps:

  • Define options once on a POCO and keep them strongly typed end-to-end
  • Avoid repetitive glue when mapping parsed values into IOptions<T>
  • Compose commands and handlers via DI in a host-friendly way

Requirements

  • .NET 8.0+
  • System.CommandLine 2.0.0

To build this repository, use the .NET 11 SDK or newer and install the .NET 8 runtime to run the tests and sample application. The library still targets .NET 8.

dotnet restore SystemCommandLine.Extensions.slnx
dotnet build SystemCommandLine.Extensions.slnx --configuration Release --no-restore
dotnet test SystemCommandLine.Extensions.slnx --configuration Release --no-build

License

MIT. See LICENSE.txt.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.0.1 95 11/24/2026
3.0.0 106 11/14/2026
2.2.0 93 11/14/2026
2.1.0 101 11/14/2026
2.0.0 50,285 11/11/2025
2.0.0-rc.2.25502.107.1 198 10/14/2025
2.0.0-rc.1.25451.107.3 232 9/20/2025
2.0.0-rc.1.25451.107.2 321 9/17/2025
2.0.0-rc.1.25451.107.1 194 9/10/2025
2.0.0-beta7.25380.108.3 201 9/7/2025
2.0.0-beta7.25380.108.1 120 8/23/2025
2.0.0-beta7.25380.108 122 8/23/2025