Cackle.ConsoleApp 2.0.3

There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package Cackle.ConsoleApp --version 2.0.3
                    
NuGet\Install-Package Cackle.ConsoleApp -Version 2.0.3
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Cackle.ConsoleApp" Version="2.0.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Cackle.ConsoleApp" Version="2.0.3" />
                    
Directory.Packages.props
<PackageReference Include="Cackle.ConsoleApp" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Cackle.ConsoleApp --version 2.0.3
                    
#r "nuget: Cackle.ConsoleApp, 2.0.3"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Cackle.ConsoleApp@2.0.3
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Cackle.ConsoleApp&version=2.0.3
                    
Install as a Cake Addin
#tool nuget:?package=Cackle.ConsoleApp&version=2.0.3
                    
Install as a Cake Tool

Cackle.ConsoleApp

Nuget License

Cackle.ConsoleApp is a lightweight library that enhances the Spectre.Console framework by introducing features commonly found in modern .NET console applications, such as:

  • Microsoft Dependency Injection (DI): Seamless integration with the standard .NET DI container.
  • IConfiguration Support: Easy access to application configuration.
  • IOptions<T> Pattern: Strongly-typed configuration management.
  • Asynchronous Commands with Cancellation: Provides an CancellableAsyncCommand base class that includes CancellationToken support and graceful handling of escape sequences (Ctrl+C).

This library aims to simplify the development of interactive console applications built with Spectre.Console, making them more maintainable and aligned with modern .NET practices.

Installation

You can install the library via NuGet Package Manager or the .NET CLI:

dotnet add package Cackle.ConsoleApp

Usage

Cackle.ConsoleApp provides a ConsoleHostBuilder to bootstrap your console application. This builder allows you to configure services, console settings, and commands in a fluent manner.

Complex Setup

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Cackle.ConsoleApp;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Spectre.Console;
using Spectre.Console.Cli;

public class Program
{
    public static Task<int> Main(string[] args)
    {
        return ConsoleHostBuilder
            // Create a new console host builder
            .Create(app =>
                app.AddCommand<GreetCommand>("greet")
                    .WithDescription("Greets the user."))

            // Configure the console host with a custom configuration
            .ConfigureServices((services, config) =>
                services.AddTransient<IGreetingService, DefaultGreetingService>())
            
            // Configure AnsiConsole settings from the "AnsiConsole" section
            .ConfigureConsole("AnsiConsole")
            
            // Build the console host
            .Build()
            
            // Run the command line application asynchronously with the provided arguments.
            .RunAsync(args);
    }
}

public interface IGreetingService
{
    string GetGreeting(string name);
}

public class DefaultGreetingService(IConfiguration config) : IGreetingService
{
    public string GetGreeting(string name)
    {
        var greetingFormat = config.GetSection("GreetingSettings")["Format"] ?? "Hello, {0}!";
        return string.Format(greetingFormat, name);
    }
}

public class GreetCommand(IGreetingService greetingService, ILogger<GreetCommand> logger)
    : CancellableAsyncCommand<GreetCommand.Settings>
{
    public override async Task<int> ExecuteAsync(CommandContext context, Settings settings,
        CancellationToken cancellationToken)
    {
        logger.LogInformation("Greeting command started for {Name}", settings.Name);
        
        await Task.Delay(100, cancellationToken);
        
        var greeting = greetingService.GetGreeting(settings.Name!);
        AnsiConsole.WriteLine(greeting);
        
        logger.LogInformation("Greeting command finished.");
        return 0;
    }

    public class Settings : CommandSettings
    {
        [CommandArgument(0, "[Name]")]
        public string? Name { get; init; }
    }
}
Explanation
  1. ConsoleHostBuilder.Create(Action<IConfigurator> configureApp): This static method initializes the host builder and allows you to configure the Spectre.Console CommandApp.
  2. app.AddCommand<GreetCommand>("greet"): Registers a command named "greet" with the Spectre.Console CLI.
  3. .ConfigureServices(Action<IServiceCollection, IConfiguration> services): Configures the application's services using the Microsoft Dependency Injection container. You have access to both the IServiceCollection and the IConfiguration.
  4. .ConfigureConsole("AnsiConsole"): Configures the global AnsiConsole.Console instance using settings from the specified configuration section (e.g., "AnsiConsole").
  5. .Build(): Builds the ConsoleHost instance.
  6. .RunAsync(string[] args): Executes the console application with the provided arguments.
  7. CancellableAsyncCommand<TSettings>: A base class for asynchronous commands that includes built-in CancellationToken support and handles Ctrl+C events gracefully.
Configuration

Cackle.ConsoleApp automatically loads configuration from appsettings.json and environment-specific appsettings.{Environment}.json files. You can access this configuration using IConfiguration in your services and commands, or through the IOptions<T> pattern for strongly-typed settings.

Example appsettings.json:

{
  "AnsiConsole": {
    "ColorSystem": "Standard",
    "Profile": {
      "Width": 80,
      "Height": 25
    }
  },
  "GreetingSettings": {
    "Format": "Welcome, {0}!"
  }
}

Async Commands with Cancellation

The CancellableAsyncCommand<TSettings> base class simplifies the creation of asynchronous console commands. It automatically handles CancellationToken propagation and provides a virtual ExecuteAsync method. It also gracefully handles Ctrl+C (CancelKeyPress) events, allowing you to perform cleanup before the application exits.

Key Components

  • ConsoleHostBuilder: The main entry point for configuring and building the console application host.
  • IConfigureConsoleHostBuilder: A fluent interface for configuring the host builder.
  • ConsoleHost: Encapsulates the Spectre.Console CommandApp and provides methods for running the application.
  • CancellableAsyncCommand<TSettings>: An abstract base class for asynchronous commands with cancellation support.
  • IAnsiConsoleFactory and AnsiConsoleFactory: Provides a factory for creating IAnsiConsole instances, integrating with IOptions<AnsiConsoleSettings>.
  • HostEnv: A static class providing access to host environment information (e.g., environment name, base directory).

Contributing

Contributions are welcome! Please feel free to submit pull requests or open issues on the GitHub repository.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Cackle.ConsoleApp:

Package Downloads
Cackle.ConsoleApp.Extensions.Logging.SpectreConsole

This library provides a logging provider for Microsoft.Extensions.Logging that utilizes the rich console output capabilities of Spectre.Console. It's designed to seamlessly integrate with the Cackle.ConsoleApp framework, offering styled and informative console logging within your Spectre.Console-powered applications.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.0.5-alpha 124 7/2/2025
2.0.3 199 5/16/2025
1.5.11 128 2/8/2025
1.5.10 155 10/25/2024
1.5.8 143 10/11/2024
1.5.7 128 10/10/2024
1.5.6 142 9/12/2024
1.5.5 145 9/4/2024
1.5.4 140 9/4/2024
1.5.3 166 8/23/2024
1.5.2 157 8/23/2024
1.5.1 154 8/23/2024
1.5.0 156 8/23/2024
1.4.0 154 8/16/2024
1.3.3 143 5/16/2024
1.3.2 135 5/10/2024
1.3.1 90 2/23/2024
1.3.0 263 11/27/2023
1.2.0-beta.1 97 10/27/2023
1.1.0 104 10/20/2023
1.0.1 70 10/19/2023
0.1.1-beta.1 99 10/7/2023
0.1.1-alpha.3 93 10/19/2023
0.1.1-alpha.2 93 10/19/2023