Skip to content

Support for use as ConfigurationProvider #524

Open

Description

@stevefan1999-personal

Is your feature request related to a problem? Please describe.
I use .NET Generic Host for my CLI application but I have multiple layers of configuration. More specifically, I want to integrate CommandLineUtils as one of the ConfigurationProvider layers.

Describe the solution you'd like
Add a way or best practice towards the use of Custom ConfigurationProvider

Describe alternatives you've considered
Having two sets of options class and copy the CLI options into Host options.

Additional context
Add any other context or screenshots about the feature request here.

Activity

  1. stevefan1999-personal commented on Nov 22, 2022

    @stevefan1999-personal
    Author

    This looks quite close to what I wanted to do

    Console.OutputEncoding = Encoding.UTF8;
    
    var cla = new CommandLineApplication<AppOptions>();
    cla.Conventions
        .UseDefaultConventions();
    var app = cla.Parse(args).SelectedCommand;
    
    var textInfo = new CultureInfo("en-US", false).TextInfo;
    var builder = Host.CreateApplicationBuilder();
    builder.Configuration.AddInMemoryCollection(app
        .GetOptions()
        .ToDictionary(x => textInfo.ToTitleCase(x.LongName), x => x.Values)
        .SelectMany(kvp => kvp.Value.Count switch
        {
            1 => Enumerable.Repeat(KeyValuePair.Create(kvp.Key, kvp.Value[0]), 1),
            > 1 => kvp.Value.Select((value, idx) => KeyValuePair.Create($"{kvp.Key}:{idx}", value)),
            _ => null
        } ?? Array.Empty<KeyValuePair<string, string?>>()));
    builder.Services.AddOptions<AppOptions>().BindConfiguration("");
    builder.Services.AddSingleton(provider =>
    {
        var options = provider.GetRequiredService<IOptions<AppOptions>>().Value;
        return new MaimaiConvertOption
        {
            ExtractImage = options.ExtractImage,
            BitRate = options.BitRate
        };
    });
    builder.Services.AddSingleton(provider =>
    {
        var option = provider.GetRequiredService<MaimaiConvertOption>();
        return new MaimaiConverter(new WindowsPath(@"C:\maimai_universe"), option);
    });
    
    builder.Services.AddHostedService<AppService>();
    using var host = builder.Build();
    host.Run();
    
    record AppOptions
    {
        [Option("--extract-image")]
        public bool ExtractImage { get; init; }
    
        [Option("-b|--bit-rate")]
        public int? BitRate { get; init; }
    
        [Option("-P|--parallelism")]
        public int Parallelism { get; init; } = 1;
        [Option("-v|--verbose", CommandOptionType.MultipleValue)]
        public bool[]? Verbose { get; init; }
    }
    
    record AppService(MaimaiConverter Converter, IOptions<AppOptions> Options, ILogger<AppService> Logger) : IHostedService
    {
        public Task StartAsync(CancellationToken cancellationToken)
        {
            var taskQueue = new List<Action>();
    
            foreach (var x in Converter.AvailableSongs?.Take(100) ?? ImmutableList<MusicData>.Empty)
            {
                async void Run()
                {
                    Logger.LogInformation($"Processing {x.CueName.Id} - {x.CueName.Str}");
                    var path = new WindowsPath("./output").Join($"{x.CueName.Id} - {x.CueName.Str}.mp3".ToValidFileName());
                    {
                        await using var memStream = new MemoryStream();
                        await Converter.ExtractMusicTrackWithJacketByMusicData(x, memStream);
    
                        await using var file = path.Open(FileMode.Create);
                        memStream.WriteTo(file);
                    }
    
                    GC.Collect();
    
                    Logger.LogInformation($"Processed {x.CueName.Str}");
                }
    
                taskQueue.Add(Run);
            }
    
            Parallel.Invoke(new() { MaxDegreeOfParallelism = Options.Value.Parallelism }, taskQueue.ToArray());
            return Task.CompletedTask;
        }
    
        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
  2. github-actions commented on Nov 23, 2023

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has no recent activity. It will be closed if no further activity occurs. Please comment if you believe this should remain open, otherwise it will be closed in 14 days. Thank you for your contributions to this project.

  3. stevefan1999-personal commented on Nov 23, 2023

    @stevefan1999-personal
    Author

    /remove-stale

  4. github-actions commented on Nov 23, 2024

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has no recent activity. It will be closed if no further activity occurs. Please comment if you believe this should remain open, otherwise it will be closed in 14 days. Thank you for your contributions to this project.

  5. stevefan1999-personal commented on Nov 23, 2024

    @stevefan1999-personal
    Author

    /remove-stale

  6. github-actions commented on Nov 24, 2025

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has no recent activity. It will be closed if no further activity occurs. Please comment if you believe this should remain open, otherwise it will be closed in 14 days. Thank you for your contributions to this project.

  7. stevefan1999-personal commented on Nov 24, 2025

    @stevefan1999-personal
    Author

    /remove-stale

  8. added
    help wantedWe would be willing to take a well-written PR to help fix this.
    on Dec 28, 2025
  9. natemcmaster commented on Dec 28, 2025

    @natemcmaster
    Owner

    I would be willing to accept a pull request to implement this. It looks like you have most of the code proposed above already. Would be part of the existing McMaster.Extensions.Hosting.CommandLine nuget package? Or should it be a separate one?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementhelp wantedWe would be willing to take a well-written PR to help fix this.

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions