Skip to content

Command Discovery

Matthias Beerens edited this page Apr 11, 2021 · 1 revision

Command Discovery

You no longer need to Add or Register Commands yourself.

You can automatically discover all commands inside an assembly that match your parser.

Configure discovery

Make sure all your Commands are setup with the same base type as the parser options model. If your parser does not have a base type you can use the normal Command class or use object as base type.

Example

using MatthiWare.CommandLine;

static void Main(string[] args)
{
    var parser = new CommandLineParser<Options>();

    // discover all available commands
    parser.DiscoverCommands(Assembly.GetCallingAssembly());

    // use parser
    var options = parser.Parse(args);
}

// Only commands with base type Options will be found and registered
public class ValidCommand1 : Command<Options, SubsetOptions>
{
   public override void OnConfigure(ICommandConfigurationBuilder<SubsetOptions> builder)
   {
       builder
          .Name("cmd1")
          .Required();
   }

   public override void OnExecute(Options options, SubsetOptions commandOptions)
   {
       Console.WriteLine("Executed command 1 with {commandOptions.Verbose}");
   }
}

public class ValidCommand2 : Command
{
   public override void OnConfigure(ICommandConfigurationBuilder builder)
   {
       builder
          .Name("cmd2")
          .Required();
   }

   public override void OnExecute()
   {
       Console.WriteLine("Executed command 2 with no options");
   }
}

public class ValidCommand3 : Command<object, SubsetOptions>
{
   public override void OnConfigure(ICommandConfigurationBuilder<SubsetOptions> builder)
   {
       builder
          .Name("cmd3")
          .Required();
   }

   public override void OnExecute(object options, SubsetOptions commandOptions)
   {
       Console.WriteLine("Executed command 3 with {commandOptions.Verbose}");
   }
}
Clone this wiki locally