Coree.NETStandard
  • API
Show / Hide Table of Contents
  • Coree.NETStandard.Abstractions.DependencySingleton
    • DependencySingleton<T>
    • IDependencySingleton
  • Coree.NETStandard.Abstractions.FluentBase
    • FluentBase
    • IFluentBase
  • Coree.NETStandard.Abstractions.InitializationService
    • InitializationDependentServices
    • InitializationService
  • Coree.NETStandard.Abstractions.ServiceFactory
    • ServiceFactory<T>
  • Coree.NETStandard.Abstractions.ServiceFactoryEx
    • ServiceFactoryEx<T>
    • ServiceFactoryEx<T, K, R, S, U, V, W, X, Y, Z>
    • ServiceFactoryEx<T, K>
    • ServiceFactoryEx<T, K, R>
    • ServiceFactoryEx<T, K, R, S>
    • ServiceFactoryEx<T, K, R, S, U>
    • ServiceFactoryEx<T, K, R, S, U, V>
    • ServiceFactoryEx<T, K, R, S, U, V, W>
    • ServiceFactoryEx<T, K, R, S, U, V, W, X>
    • ServiceFactoryEx<T, K, R, S, U, V, W, X, Y>
  • Coree.NETStandard.Classes.AsyncEventCollection
    • AsyncEventCollection<T>
    • AsyncEventCollection<T>.CustomEventDelegate
  • Coree.NETStandard.Classes.CommonDistinguishedNameBuilder
    • CommonDistinguishedNameBuilder
    • DistinguishedName
  • Coree.NETStandard.Classes.Criteria
    • CriteriaComparisonMethod
    • CriteriaEnumerableExtensions
    • CriteriaExpressionBuilder
    • CriteriaItem<TValue>
    • CriteriaItems
    • CriteriaOperator
    • CriteriaQueryableExtensions
  • Coree.NETStandard.Classes.HttpRequestService
    • ContentComposer
    • HttpRequestHeadersExtensions
    • HttpRequestService
    • HttpRequestServiceHandler
    • HttpRequestServiceUriExtensions
    • ServiceCollectionExtensions
    • TransactionRecord
  • Coree.NETStandard.Classes.Scheduler
    • Scheduler
    • Scheduler.TickerEventArgs
    • Scheduler.TickerEventDelegate
  • Coree.NETStandard.Classes.ThreadSafeCollection
    • ThreadSafeCollection<T>
  • Coree.NETStandard.Classes.ThreadSafeValue
    • ThreadSafeValue<T>
  • Coree.NETStandard.Classes.TimeOfDay
    • TimeOfDay
  • Coree.NETStandard.Extensions.Collections.Enumerable
    • CollectionsEnumerableExtensions
  • Coree.NETStandard.Extensions.Collections.List
    • CollectionsListExtensions
  • Coree.NETStandard.Extensions.Conversions.ByteArray
    • ConversionsByteArrayExtensions
  • Coree.NETStandard.Extensions.Conversions.HostApplicationBuilder
    • ConversionsHostApplicationBuilderExtensions
  • Coree.NETStandard.Extensions.Conversions.String
    • ConversionsStringExtensions
    • Encodings
  • Coree.NETStandard.Extensions.Conversions.Stringbuilder
    • ConversionsStringbuilderExtension
  • Coree.NETStandard.Extensions.Enums
    • EnumExtensions
  • Coree.NETStandard.Extensions.Http.HttpHeader
    • HttpHeadersExtensions
  • Coree.NETStandard.Extensions.Primitives.Bool
    • PrimitivesBoolExtensions
  • Coree.NETStandard.Extensions.Reflection.ServiceProvider
    • ReflectionServiceProviderExtensions
  • Coree.NETStandard.Extensions.ServiceCollection
    • ServiceCollectionExtensions
  • Coree.NETStandard.Extensions.Threading.CancellationToken
    • ThreadingCancellationTokenExtensions
  • Coree.NETStandard.Extensions.Utilities
    • DateTimeExtensions
  • Coree.NETStandard.Extensions.Validations.String
    • ValidationsStringExtensions
  • Coree.NETStandard.HostedServicesCollection
    • HostedServicesCollectionConfig<T>
    • IHostedServicesCollectionConfig<T>
    • ServiceCollectionExtensions
    • ServiceProviderExtensions
  • Coree.NETStandard.Serilog
    • ConditionalLevelSink
    • CustomTheme
    • LoggerSinkConfigurationExtensions
    • OutputTemplates
    • ServiceCollectionExtensions
    • SourceContextShortEnricher
  • Coree.NETStandard.Services.DebugManagement
    • DebugService
    • IDebugService
  • Coree.NETStandard.Services.DirectoryOperationsManagement
    • DirectoryOperationsService
    • IDirectoryOperationsService
  • Coree.NETStandard.Services.FileManagement
    • FileService
    • IFileService
  • Coree.NETStandard.Services.FileOperationsManagement
    • FileOperationsService
    • FileOperationsService.FileSystemEntry
    • FileOperationsService.FileSystemInformation
    • FileOperationsService.VerifiedCopyStatus
    • IFileOperationsService
  • Coree.NETStandard.Services.HashManagement
    • HashService
    • IHashService
  • Coree.NETStandard.Services.NetworkManagement
    • INetworkService
    • NetworkService
    • NetworkService.IpAdressInformation
    • NetworkService.NetworkInterfaceDetail
  • Coree.NETStandard.Services.ProcessManagement
    • IProcessService
    • ProcessRunExitCodeState
    • ProcessRunResult
    • ProcessService
  • Coree.NETStandard.Services.RuntimeInsightsManagement
    • IRuntimeInsightsService
    • RuntimeInsightsService
  • Coree.NETStandard.SpectreConsole
    • CommandAppExtensions
    • HostBuilderExtensions
    • ServiceCollectionExtensions
    • SpectreConsoleHostedService
    • SpectreConsoleHostedService.ExitCode
    • SpectreConsoleTypeRegistrar
    • SpectreConsoleTypeResolver
  • Coree.NETStandard.UnderConstruction
    • DbContextExtensions
    • HttpClientStatic
    • HttpClientStatic.HttpClientResponse
    • HttpClientStatic.XRate
    • HttpClientStatic.XRateGroup
    • HttpClientStatic.XRateItem
    • IScheduleProvider
    • IntervalScheduleProvider
    • LimitedHistory<T>
    • ScheduleCombiner
    • Scheduler
    • Scheduler.TickerEventArgs
    • Scheduler.TickerEventDelegate
    • Scheduler2
    • Scheduler2.TickerEventArgs
    • Scheduler2.TickerEventDelegate
    • Scheduler3
    • Scheduler3.TickerEventArgs
    • Scheduler3.TickerEventDelegate
    • SqlliteMemoryContext
    • SqlliteMemoryContext.UserDataDto
    • TimedEntry<T>
    • Timing
    • Timing.Ticker
    • Timing.Ticker.TickerEventArgs
    • Timing.TickerSync
    • WeekDayAtScheduleProvider
  • Coree.NETStandard.Utilities
    • EventSubscription
    • MainContext

Class HostBuilderExtensions

Provides extension methods for IHostBuilder to facilitate the integration of Spectre.Console's CommandApp into the application's host builder.

Inheritance
object
HostBuilderExtensions
Inherited Members
object.Equals(object)
object.Equals(object, object)
object.GetHashCode()
object.GetType()
object.MemberwiseClone()
object.ReferenceEquals(object, object)
object.ToString()
Namespace: Coree.NETStandard.SpectreConsole
Assembly: Coree.NETStandard.dll
Syntax
public static class HostBuilderExtensions

Methods

| Edit this page View Source

UseSpectreConsole(IHostBuilder, Action<IConfigurator>, bool)

Configures the application's host builder to use Spectre.Console's Spectre.Console.Cli.CommandApp and related services. This setup enables the application to utilize Spectre.Console's command line interface tools, allowing for the definition, parsing, and execution of commands within a .NET Core application.

Declaration
public static IHostBuilder UseSpectreConsole(this IHostBuilder builder, Action<IConfigurator> configureCommandApp, bool suppressLifeTimeStatusMessages = true)
Parameters
Type Name Description
IHostBuilder builder

The IHostBuilder to configure.

Action<IConfigurator> configureCommandApp

An Action<T> delegate that configures the Spectre.Console.Cli.CommandApp.

bool suppressLifeTimeStatusMessages

Supresses default output of the application host.

Returns
Type Description
IHostBuilder

The IHostBuilder so that additional configuration calls can be chained.

Remarks

This method performs the following operations:

  • Creates and configures a new instance of Spectre.Console.Cli.CommandApp using the provided configureCommandApp action.
  • Scans for command types within the Spectre.Console.Cli.CommandApp and registers them as singletons in the service collection.
  • Registers the Spectre.Console.Cli.CommandApp as a singleton service, configured to use a SpectreConsoleTypeRegistrar for dependency injection.
  • Adds a SpectreConsoleHostedService to the services collection to manage the lifecycle of the Spectre.Console.Cli.CommandApp within the host application.
static async Task Main(string[] args)
{
    var builder = Host.CreateDefaultBuilder(args);
    builder.ConfigureServices(services =>
    {
        services.AddSingleton<ISomeServiceDependency, SomeServiceDependency>();
        services.AddHostedService<SomeOtherBackgroundService>();
    });
    builder.UseSpectreConsole(configCommandApp =>
    {
        configCommandApp.SetApplicationName("testapp");
        configCommandApp.AddCommand<MyAsyncCommand>("my-command");
    });
    await builder.Build().RunAsync();
}

public class MyAsyncCommand : AsyncCommand<MyAsyncCommand.Settings>
{
    private readonly ISomeServiceDependency dependencyService; private readonly IHostApplicationLifetime appLifetime;

    public MyAsyncCommand(ISomeServiceDependency dependencyService, IHostApplicationLifetime appLifetime)
    {
        this.dependencyService = dependencyService; this.appLifetime = appLifetime;
    }

    public class Settings : CommandSettings
    {
        [Description("The commandline setting")]
        [CommandArgument(0, "<Setting>")]
        public string? SomeSetting { get; init; }
    }

    public override async Task<int> ExecuteAsync(CommandContext context, Settings settings)
    {
        try { await dependencyService.PerformConsoleAction(appLifetime.ApplicationStopping); }
        catch (Exception) { return (int)SpectreConsoleHostedService.ExitCode.CommandTerminated; }
        return (int)SpectreConsoleHostedService.ExitCode.SuccessAndContinue;
    }
}
Exceptions
Type Condition
ArgumentNullException

Thrown if builder is null.

| Edit this page View Source

UseSpectreConsoleSyncCommandExecutor(IHostBuilder, Action<IConfigurator>, bool)

Sets up a command execution environment within the application's host configuration, where commands are executed synchronously. This method creates an entry point for a command-line application that supports multiple commands, each running in a synchronous manner within its own task context. In the event of a service cancellation, the currently executing command will be terminated abruptly.

Declaration
public static IHostBuilder UseSpectreConsoleSyncCommandExecutor(this IHostBuilder builder, Action<IConfigurator> configureCommandApp, bool suppressLifeTimeStatusMessages = true)
Parameters
Type Name Description
IHostBuilder builder

The host builder to configure, which is augmented with services and configurations necessary for managing command execution.

Action<IConfigurator> configureCommandApp

A delegate that configures the command-line application, facilitating the registration and setup of individual commands.

bool suppressLifeTimeStatusMessages

Optional. Determines whether to suppress host lifetime status messages, with a default value of true. When set to false, these messages are made visible, offering insights into the lifecycle events of the host.

Returns
Type Description
IHostBuilder

The host builder, now configured with the synchronous command execution environment, ready for further configuration or immediate use.

Remarks
static async Task Main(string[] args)
{
    var builder = Host.CreateDefaultBuilder(args);
    builder.ConfigureServices(services =>
    {
        services.AddSingleton<ISomeServiceDependency, SomeServiceDependency>();
        services.AddHostedService<SomeOtherBackgroundService>();
    });
    builder.UseSpectreConsoleSyncCommandExecutor(configCommandApp =>
    {
        configCommandApp.SetApplicationName("testapp");
        configCommandApp.AddCommand<MyAsyncCommand>("my-command");
    });
    await builder.Build().RunAsync();
}

public class MyAsyncCommand : AsyncCommand<MyAsyncCommand.Settings> { private readonly ISomeServiceDependency dependencyService; private readonly IHostApplicationLifetime appLifetime;

public MyAsyncCommand(ISomeServiceDependency dependencyService, IHostApplicationLifetime appLifetime)
{
    this.dependencyService = dependencyService;
    this.appLifetime = appLifetime;
}

public class Settings : CommandSettings
{
    [Description("The commandline setting")]
    [CommandArgument(0, "<Setting>")]
    public string? SomeSetting { get; init; }
}

public override async Task<int> ExecuteAsync(CommandContext context, Settings settings)
{
    // Attempts to abort the command gracefully will fail because the command runs on a separate task and not in the service host's managed context.
    try {
        await dependencyService.PerformConsoleAction(appLifetime.ApplicationStopping);
    }
    catch (Exception)
    {
        // This catch block is unreachable. The service host's abrupt termination of the command prevents this block from being executed.
        return (int)SpectreConsoleHostedService.ExitCode.CommandTerminated;
    }
    // It's crucial to explicitly manage the service host's state after command execution completes, either continuing operation or initiating shutdown.
    return (int)SpectreConsoleHostedService.ExitCode.SuccessAndContinue;
}

}

Exceptions
Type Condition
ArgumentNullException

Thrown if the provided host builder is null, ensuring method reliability and preventing null reference errors.

  • Edit this page
  • View Source
In this article
Back to top