Skip to content

CommandLine

CloudFy edited this page Feb 14, 2025 · 1 revision

About

Extends System.CommandLine with dependency injection registration and handler separation of commands.

Installation

dotnet add package Arcturus.Extensions.CommandLine

Usage

Start a new Console application project. Install the package and then use the following boiler plate in Program.cs.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.CommandLine.Builder;
using Arcturus.CommandLine;

var builder = Host.CreateDefaultBuilder(args)
    .ConfigureServices((context, services) =>
    {
        services.AddSingleton<..some service...>();

        services.AutoRegisterCommandHandlers(); // registers all ICommandHandlers
    })
    .ConfigureCommandLineBuilder((commandLineBuilder) => {
        commandLineBuilder.UseDefaults();
        commandLineBuilder.UseExceptionHandler((exception, context) =>
        {
            .. handle exceptions with grace ...
        });
    });
var host = builder.Build();

await host.RunConsoleCommands<Commands.RootCommand>(args);

You will have to setup a RootCommand which is the top-level command for all sub commands. The root-command does not need any handler, however all sub commands should be registered using the [SubCommand(...)] attribute:

[Command(
    "CLI"
    , "This is our CLI description")]
[SubCommand(
    typeof(DoSomethingCommand))]
public class RootCommand : ICommand
{
}

A sub command is the handled as the following example:

// used via 'cli {dosomething}'
[Command("dosomething", "example command")]
public class DoSomethingCommand : ICommand
{
    public string? Text { get; set; }
}
public class DoSomethingCommandHandler(
    SomeDiService someDiService) // illustration only
    : ICommandHandler<DoSomethingCommand>
{
    private readonly SomeDiService _someDiService = someDiService; // illustration only

    public ValueTask Handle(DoSomethingCommand command, CancellationToken cancellationToken)
    {
        Console.WriteLine(command.Text ?? "No text provided);
        return ValueTask.CompletedTask;
    }
}

Using the API

Commands

Options

Arguments

Customizing command line building

Clone this wiki locally