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 ServiceCollectionExtensions

Provides extension methods for IServiceCollection to facilitate the integration of Spectre.Console's CommandApp.

Inheritance
object
ServiceCollectionExtensions
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 ServiceCollectionExtensions

Methods

| Edit this page View Source

AddSpectreConsole(IServiceCollection, Action<IConfigurator>, bool)

Adds and configures Spectre.Console's Spectre.Console.Cli.CommandApp and related services to the specified IServiceCollection. This setup allows for utilizing Spectre.Console's command line interface tools within a .NET Core application, enabling the definition, parsing, and execution of commands.

Declaration
public static IServiceCollection AddSpectreConsole(this IServiceCollection services, Action<IConfigurator> configureCommandApp, bool suppressLifeTimeStatusMessages = true)
Parameters
Type Name Description
IServiceCollection services

The IServiceCollection to add services to.

Action<IConfigurator> configureCommandApp

An Action delegate that is used to configure the Spectre.Console.Cli.CommandApp.

bool suppressLifeTimeStatusMessages

Supresses default output of the application host.

Returns
Type Description
IServiceCollection

The IServiceCollection so that additional calls can be chained.

Remarks

This method performs the following operations:

  • Initializes a new instance of Spectre.Console.Cli.CommandApp and configures it using the provided configureCommandApp action.
  • Scans for command types registered within the Spectre.Console.Cli.CommandApp and registers them as singletons in the service collection.
  • Registers the Spectre.Console.Cli.CommandApp itself as a singleton service, configured to use a SpectreConsoleTypeRegistrar for dependency injection.
  • Adds a SpectreConsoleHostedService, to manage the application lifecycle of the Spectre.Console.Cli.CommandApp.
static async Task Main(string[] args)
{
    var builder = Host.CreateDefaultBuilder(args);
    builder.ConfigureServices(services =>
    {
        services.AddSpectreConsole(configCommandApp =>
        {
            configCommandApp.SetApplicationName("testapp");
            configCommandApp.AddCommand<MyAsyncCommand>("my-command");
        });
        services.AddSingleton<ISomeServiceDependency, SomeServiceDependency>();
        services.AddHostedService<SomeOtherBackgroundService>();
    });
    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;
    }
}
| Edit this page View Source

AddSpectreConsoleSyncCommandExecutor(IServiceCollection, Action<IConfigurator>, bool)

Registers a command execution environment with Spectre.Console integration into the application's service collection. This setup facilitates the execution of command-line commands synchronously within their own task contexts. Designed to support multiple commands, this configuration allows for abrupt termination of commands upon service cancellation, ensuring immediate response to stop requests.

Declaration
public static IServiceCollection AddSpectreConsoleSyncCommandExecutor(this IServiceCollection services, Action<IConfigurator> configureCommandApp, bool suppressLifeTimeStatusMessages = true)
Parameters
Type Name Description
IServiceCollection services

The IServiceCollection to configure, which is augmented with the necessary services and configurations for Spectre.Console command execution.

Action<IConfigurator> configureCommandApp

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

bool suppressLifeTimeStatusMessages

Optional. Determines whether to suppress host lifetime status messages, with a default value of true. Setting this to false enables the visibility of these messages, providing insights into the lifecycle events of the host and command execution.

Returns
Type Description
IServiceCollection

The IServiceCollection, now configured with the Spectre.Console command execution environment, ready for further configuration or immediate use within the application's startup process.

Remarks

Integrating the Spectre.Console command executor into your services collection. Commands are executed synchronously but in a separate task. Note that attempts to abort commands gracefully will face challenges due to their execution in separate tasks, which are not managed by the service host's context.

static async Task Main(string[] args)
{
    var builder = Host.CreateDefaultBuilder(args);
    builder.ConfigureServices(services =>
    {
        services.AddSingleton<ISomeServiceDependency, SomeServiceDependency>();
        services.AddHostedService<SomeOtherBackgroundService>();
        services.AddSpectreConsoleSyncCommandExecutor(configureCommandApp =>
        {
            configureCommandApp.SetApplicationName("toolkit");
            configureCommandApp.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;
    }
}
  • Edit this page
  • View Source
In this article
Back to top