Skip to content

Commands

Adam Bajguz edited this page Apr 5, 2021 · 7 revisions

Defining commands

In order to add functionality to your application, you need to define at least one command. Commands are essentially entry points through which the user can interact with your application. You can think of them as something similar to controllers in ASP.NET Core.

To define a command, just create a new class that implements the ICommand interface and annotate it with [Command] attribute:

[Command]
public class HelloWorldCommand : ICommand
{
    public ValueTask ExecuteAsync(IConsole console)
    {
        console.Output.WriteLine("Hello world!");

        // Return empty task because our command executes synchronously
        return default;
    }
}

To implement ICommand, the class needs to define an ExecuteAsync method. This is the method that gets by called Typin when the user executes the command.

To facilitate both asynchronous and synchronous execution, this method returns a ValueTask. Since the simple command above executes synchronously, we can just put return default at the end. In an asynchronous command, however, we would use the async/await keywords instead.

As a parameter, this method takes an instance of IConsole, an abstraction around the system console. You should use this abstraction in places where you would normally interact with System.Console, in order to make your command testable.

With this basic setup, the user can execute your application and get a greeting in return:

> myapp.exe

Hello world!

Options and parameters

Commands may have parameters and options through [CommandParameter] and [CommandOption].

Read more about parameters and options in Binding arguments.

Help and version options

Out of the box, your application now also supports the built-in help and version options:

For each command, you can specify a description and manual. A manual is simply a longer, usually multiline, text that is display at the end of help.

> myapp.exe --help

MyApp v1.0

Usage
  myapp.exe

Options
  -h|--help         Shows help text.
  --version         Shows version information.

In help screen commands and directives marked with @ cannot be executed in every mode in the app, while required options and parameters have *.

Read more about help in Help system.

> myapp.exe --version

v1.0
Clone this wiki locally