From b4a83160c5320ecec873c28c95193498eb5e1627 Mon Sep 17 00:00:00 2001 From: Kyle Burrows Date: Tue, 20 Jan 2026 19:52:59 -0500 Subject: [PATCH] Setup root command after building IHost and pass into MinimalCommandLineApp --- src/MinimalCli.Core/MinimalCommandLineApp.cs | 15 ++++++++---- .../MinimalCommandLineBuilder.cs | 24 ++++++++++++++++--- 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/src/MinimalCli.Core/MinimalCommandLineApp.cs b/src/MinimalCli.Core/MinimalCommandLineApp.cs index 63ca4fb..83ea857 100644 --- a/src/MinimalCli.Core/MinimalCommandLineApp.cs +++ b/src/MinimalCli.Core/MinimalCommandLineApp.cs @@ -15,13 +15,18 @@ public class MinimalCommandLineApp : IHostedService private CommandExecutorCli CliCommandExecutor => this.Services.GetRequiredService(); private CommandExecutorShell ShellCommandExecutor => this.Services.GetRequiredService(); - internal MinimalCommandLineApp(MinimalCommandLineBuilder builder, string[] args) + internal MinimalCommandLineApp( + IHost host, + CommandExecutionMode executionMode, + RootCommand root, + IConfiguration config, + string[] args) { - this.Host = builder.builder.Build(); - this.cmdExecutionMode = builder.cmdExecutionMode; - this.Configuration = builder.Configuration; + this.Host = host; + this.cmdExecutionMode = executionMode; + this.Configuration = config; + this.RootCommand = root; this.args = args; - this.RootCommand = builder.RootCommand; } internal readonly Dictionary> ArgumentParsers = new(); diff --git a/src/MinimalCli.Core/MinimalCommandLineBuilder.cs b/src/MinimalCli.Core/MinimalCommandLineBuilder.cs index 166ff78..a68480c 100644 --- a/src/MinimalCli.Core/MinimalCommandLineBuilder.cs +++ b/src/MinimalCli.Core/MinimalCommandLineBuilder.cs @@ -59,7 +59,7 @@ public MinimalCommandLineApp Build() this.Services.AddSingleton(cmdBindingFactory); // check if there was a generated root command - var rootOptions = commandOptionsCollection.FirstOrDefault(opt => opt.Command is RootCommand); + CommandOptions? rootOptions = commandOptionsCollection.FirstOrDefault(opt => opt.Command is RootCommand); if (rootOptions is not null) { this.RootCommand = (RootCommand)rootOptions.Command; @@ -119,8 +119,26 @@ public MinimalCommandLineApp Build() //} } - // pass in args from builder - MinimalCommandLineApp app = new(this, this.args); + if (this.RootCommand is null) + throw new InvalidOperationException("RootCommand should not be null here"); + + // build host + IHost host = this.builder.Build(); + + // setup root command here + if (rootOptions is not null) + { + var rootAction = rootOptions.Handler(host.Services); + this.RootCommand.SetAction(rootAction); + } + + MinimalCommandLineApp app = new( + host, + this.cmdExecutionMode, + this.RootCommand, + this.Configuration, + this.args + ); return app; }