dotnet / dotnet/command-line-api
`Service not found for type` when using `Command.SetHandler<...>`
- Dominant language
- C#
- Stars
- 3.7k
- Forks
- 428
- PR merge metrics
- No merged PRs in 30d
Description
version used: `2.0.0-beta2.21617.1`
When using the new way to set a handler for a command (`SetHandler`) there is an error saying `Service not found for type ..`.
When using the old(er) way to set the handler everything is working.
```cs
namespace MyNamespace
{
class Program
{
private static Task Main(string[] args)
{
var rootCommand = new RootCommand(description: "the root command");
addTestCommand(rootCommand);
return rootCommand.InvokeAsync(args);
}
private static void addTestCommand(RootCommand rootCommand)
{
var testCommand = new Command("test", "a simple command for tests")
{
new Option(
"--int-option",
getDefaultValue: () => 42,
description: "An option whose argument is parsed as an int"),
new Option(
"--bool-option",
"An option whose argument is parsed as a bool"),
new Option(
"--file-option",
"An option whose argument is parsed as a FileInfo").ExistingOnly()
};
//set up handler the new recommended way --> error
testCommand.SetHandler((intOption, boolOption, fileOption, verbose, console) =>
{
if (verbose)
{
console.Out.Write("Command used: 'test'");
console.Out.Write(Environment.NewLine);
}
console.Out.Write($"The value for --int-option is: {intOption}");
console.Out.Write(Environment.NewLine);
console.Out.Write($"The value for --bool-option is: {boolOption}");
console.Out.Write(Environment.NewLine);
console.Out.Write($"The value for --file-option is: {fileOption?.FullName ?? "null"}");
console.Out.Write(Environment.NewLine);
if (verbose)
{
console.Out.Write($"Done!");
}
});
////set up handler the old way --> works
////needs package System.CommandLine.NamingConventionBinder
//testCommand.Handler = System.CommandLine.NamingConventionBinder.CommandHandler.Create(HandleTest);
//static void HandleTest(int intOption, bool boolOption, FileInfo fileOption, bool verbose, IConsole console)
//{
// if (verbose)
// {
// console.Out.Write("Command used: 'test'");
// console.Out.Write(Environment.NewLine);
// }
// console.Out.Write($"The value for --int-option is: {intOption}");
// console.Out.Write(Environment.NewLine);
// console.Out.Write($"The value for --bool-option is: {boolOption}");
// console.Out.Write(Environment.NewLine);
// console.Out.Write($"The value for --file-option is: {fileOption?.FullName ?? "null"}");
// console.Out.Write(Environment.NewLine);
// if (verbose)
// {
// console.Out.Write($"Done!");
// }
//}
rootCommand.AddCommand(testCommand);
}
}
}
```

Contributor guide
Assessment
This issue has not been assessed yet.