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

Unable to cast object of type 'System.CommandLine.Invocation.AnonymousSynchronousCommandLineAction' to type 'System.CommandLine.Invocation.AsynchronousCommandLineAction'

Open Peter-Juhasz opened this issue 6 months ago • 0 comments

using System.CommandLine;
using System.CommandLine.Hosting;

await BuildCommandLine()
    .UseHost()
    .InvokeAsync(args);

static CommandLineConfiguration BuildCommandLine()
{
    var root = new RootCommand();
    var sub = new Command("sub", "A subcommand that does something.");
    sub.SetAction(result => // resolves to Action<ParseResult>
    {
        Console.WriteLine("Subcommand executed successfully!");
    });
    root.Add(sub);
    var config = new CommandLineConfiguration(root);
    config.ThrowIfInvalid();
    return config;
}
System.InvalidCastException: Unable to cast object of type 'System.CommandLine.Invocation.AnonymousSynchronousCommandLineAction' to type 'System.CommandLine.Invocation.AsynchronousCommandLineAction'.
   at System.CommandLine.Hosting.HostingAction.SetHandlers(Command command, Func`2 hostBuilderFactory, Action`1 configureHost)
   at System.CommandLine.Hosting.HostingAction.SetHandlers(Command command, Func`2 hostBuilderFactory, Action`1 configureHost)
   at System.CommandLine.Hosting.HostingExtensions.UseHost(CommandLineConfiguration config, Func`2 hostBuilderFactory, Action`1 configureHost)
   at System.CommandLine.Hosting.HostingExtensions.UseHost(CommandLineConfiguration config, Action`1 configureHost)
   at Program.<Main>$(String[] args) in REDACTED\Program.cs:line 4
   at Program.<Main>(String[] args)

It does work without UseHost()˙.

Peter-Juhasz avatar Jun 09 '25 18:06 Peter-Juhasz