I am using VS 2022, .Net 6.0, and trying to build my first app with System.CommandLine.
Problem: when I build it, I get a complaint that The name 'CommandHandler' does not exist in the current context
The code I'm trying to build is the sample app from the GitHub site: https://github.com/dotnet/command-line-api/blob/main/docs/Your-first-app-with-System-CommandLine.md , without alteration (I think).
It looks like this:
using System;
using System.CommandLine;
using System.IO;
static int Main(string[] args)
{
// Create a root command with some options
var rootCommand = new RootCommand
{
new Option<int>(
"--int-option",
getDefaultValue: () => 42,
description: "An option whose argument is parsed as an int"),
new Option<bool>(
"--bool-option",
"An option whose argument is parsed as a bool"),
new Option<FileInfo>(
"--file-option",
"An option whose argument is parsed as a FileInfo")
};
rootCommand.Description = "My sample app";
// Note that the parameters of the handler method are matched according to the names of the options
rootCommand.Handler = CommandHandler.Create<int, bool, FileInfo>((intOption, boolOption, fileOption) =>
{
Console.WriteLine($"The value for --int-option is: {intOption}");
Console.WriteLine($"The value for --bool-option is: {boolOption}");
Console.WriteLine($"The value for --file-option is: {fileOption?.FullName ?? "null"}");
});
// Parse the incoming args and invoke the handler
return rootCommand.InvokeAsync(args).Result;
}
I have installed the latest version of System.Commandline: 2.0.0-beta2.21617.1
SURELY I am just being a big fat idiot in some respect. But I don't see it.
Any insight would be welcomed.
CodePudding user response:
This issue is caused by updating the CommandLine 2.0 Beta 2 package. Add the reference System.CommandLine.NamingConventionBinder
to the references to fix the problem. Follow the announcements on command-line-api's GitHub account:
> In your project, add a reference to System.CommandLine.NamingConventionBinder.
> In your code, change references to the System.CommandLine.Invocation namespace to
use System.CommandLine.NamingConventionBinder, where the CommandHandler.Create
methods are now found. (There’s no longer a CommandHandler type in
System.CommandLine, so after you update you’ll get compilation errors until you
reference System.CommandLine.NamingConventionBinder.)
If you want to continue with the old habits, try using older versions of the System.CommandLine
package.
Resources
CodePudding user response:
Think you're missing a using
line:
using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.IO;
I can't swear that's it, but it looks like CommandHandler
is defined in a namespace not referenced by a using
(in your current code), so System.CommandLine.Invocation
may be the key!