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

Hosting root-command with sub-command returns abnormal error

Open Kayuse88 opened this issue 2 years ago • 1 comments

I have found wired error when using System.CommandLine.Hosting with DI.

var rootCommand = new CustomRootCommand();
rootCommand.AddCommand(new CustomCommand()); // the code will works if I comment this line

var runner = new CommandLineBuilder(rootCommand)
	.UseHost(host => host
		.UseCommandHandler<CustomRootCommand, CustomRootHandler>()
		.UseCommandHandler<CustomCommand, CustomHandler>())
	.UseDefaults()
	.Build();

There's main root-command and a sub-command as child. When I ran the app to invoke root-command with argument, It returned an error "Required command was not provided.". But if I remove the sub-command, It works normally.

https://github.com/dotnet/command-line-api/blob/42c58533cdf478b15120542be76f7cbaacaab024/src/System.CommandLine/Parsing/CommandResult.cs#L48-L55

Code snippet shows that it should return error if handler is null. I figured out error check occured before DI command handler. "HasSubcommands" condition explains why it works without error if I remove sub-command from root-command. If I inject command handler manually like below, it works.

rootCommand.Handler = CommandHandler.Create(typeof(CustomRootHandler).GetMethod(nameof(ICommandHandler.InvokeAsync)));

Is there a way to fix it without forced injection before the host building process?

Kayuse88 avatar Mar 16 '23 08:03 Kayuse88

Any update on this? I am getting the same issue

emanuel-v-r avatar Dec 21 '23 17:12 emanuel-v-r