System.CommandLine is a really handy .Net library for parsing command line arguments passed to an application. Unfortunately some useful features available in its beta stage were removed from the library's release candidates. CommandLineX brings back some of them: hosting extensions and arguments model binding including DI.
- Open terminal in the directory where your project usually are located.
- Execute
dotnet new console -n MyConsoleApp --no-restore
- Navigate to the project directory.
- Open
MyConsoleApp.csprojin XML editor of your choice. - Change project SDK by replacing
<Project Sdk="Microsoft.NET.Sdk">with<Project Sdk="Microsoft.NET.Sdk.Worker">(needed for hosting integration).
In the directory of your project execute
dotnet add package diVISION.CommandLineX- Create
MyFirstAction.cs(command action model) in your project directory:using diVISION.CommandLineX; namespace MyConsoleApp { public class MyFirstAction(ILogger<MyFirstAction> logger): ICommandAction { // injected by the host via DI private readonly ILogger<MyFirstAction> _logger = logger; // "do-amount" argument public IEnumerable<int> DoAmount { get; set; } = [0]; // "--directory" option public DirectoryInfo Directory { get; set; } = new ("."); public int Invoke(CommandActionContext context) { return InvokeAsync(context).Result; } public Task<int> InvokeAsync(CommandActionContext context, CancellationToken cancellationToken = default) { _logger.LogDebug("Starting work"); Console.WriteLine($"Doing it {string.Join(" then ", DoAmount)} times on {Directory.FullName}"); return Task.FromResult(DoAmount.FirstOrDefault()); } } }
- Modify
Program.cs(Mainmethod resp. depending on whether--use-program-mainoption used withdotnet new):using diVISION.CommandLineX.Hosting; using System.CommandLine; var rootCmd = new RootCommand("Running commands"); var builder = Host.CreateDefaultBuilder(args); builder .ConfigureAppConfiguration((config) => { config.SetBasePath(AppDomain.CurrentDomain.BaseDirectory); }) .ConfigureDefaults(null) .UseConsoleLifetime() // next 2 calls initalize CommandLine hosting .UseCommandLine(rootCmd) .UseCommandWithAction<MyFirstAction>(rootCmd, new("myFirst", "Doing things") { new Argument<IEnumerable<int>>("do-amount") { Arity = new(1, 2) }, new Option<DirectoryInfo>("-d", ["--directory"]) { Description = "Some directory to use", DefaultValueFactory = (_) => new DirectoryInfo(".") } }); using var host = builder.Build(); return await host.RunCommandLineAsync(args);
Execute one of the following in your project directory
dotnet run -- myFirst 42dotnet run -- myFirst 42 43dotnet run -- myFirst 42 43 -d someOtherDirectoryYou can also request help on commands like
dotnet run -- -?dotnet run -- myFirst -?For building the application .NET SDK 8.x is required (recommended: Visual Studio or Visual Studio Code).
After cloning the repository you can either open the solution CommandLineX.sln in your IDE and hit "Build" or open the terminal in the solution directory and execute
dotnet buildAll contributions to development and error fixing are welcome. Please always use develop branch for forks and pull requests, main is reserved for stable releases and critical vulnarability fixes only. Please note: all code changes should meet minimal code coverage requirements to be merged into main or develop.