command-line-api icon indicating copy to clipboard operation
command-line-api copied to clipboard

UseHost() - Can't assign HelpAction() to root command or synchronous action to any command

Open seanadams9 opened this issue 2 years ago • 2 comments

In my app want to set the action of the root command to a HelpAction to display help if no subcommand is specified. This worked until the PR to split actions into Async and Sync. If any command actions were synchronous then this will throws as well with unable to cast SynchronousAction to AsynchronousAction.

Unable to cast object of type 'System.CommandLine.Help.HelpAction' to type 'System.CommandLine.Invocation.AsynchronousCliAction'. System.InvalidCastException: Unable to cast object of type 'System.CommandLine.Help.HelpAction' to type 'System.CommandLine.Invocation.AsynchronousCliAction'. at System.CommandLine.Hosting.HostingAction.SetHandlers(CliCommand command, Func2 hostBuilderFactory, Action1 configureHost) at System.CommandLine.Hosting.HostingExtensions.UseHost(CliConfiguration builder, Func2 hostBuilderFactory, Action1 configureHost)

seanadams9 avatar Jun 13 '23 02:06 seanadams9

This caught me out as well. I ended up wrapping up the HelpAction in an AsynchronousCliAction and setting it using the action property on the command. I don't love this solution though and it wasn't clear to me (and still isn't) why this causes an issue.

(I started getting the error after I introduced System.CommandLine.Hosting)

barrygiles avatar Mar 25 '24 09:03 barrygiles

This seems problematic.

THandler will be of type CliAction, from which both SynchronousCliAction and AsynchronousCliAction derive, but the method only refers to AsynchronousCliAction.InvokeAsync.

https://github.com/dotnet/command-line-api/blob/5ea97af07263ea3ef68a18557c8aa3f7e3200bda/src/System.CommandLine.Hosting/HostingExtensions.cs#L60-L66

barrygiles avatar Mar 26 '24 10:03 barrygiles