command-line-api icon indicating copy to clipboard operation
command-line-api copied to clipboard

Guidance on how to use Configuration and DI APIs

Open Kralizek opened this issue 2 years ago • 1 comments

Hi, I'm sorry if issues aren't the proper place for this kind of posts but I couldn't find the discussion board.

I've recently created an console application that reuses services that are mainly designed to be hosted in a ASP.NET Core application and thus relying on APIs like Configuration, ServiceCollection/Provider and so on.

I was able to get something working (see this gist) but I'm quite unhappy on how bloated the handler looks like.

I've tried to use the System.CommandLine.Hosting package and I've played around with the HostingPlayground sample. I got to this gist but I'm a bit at loss on how to push into the configuration system the values coming from arguments (e.g. AWS profile name and region). Same goes on how to access the Configuration when registering services.

Thanks.

Kralizek avatar May 17 '22 09:05 Kralizek

There's an override with HostBuilderContext, you can access the Configuration with context.Configuration, hope it helps

    .UseHost(hostBuilder =>
    {
        hostBuilder.ConfigureServices((context, services) =>
        {
            context.Configuration.GetConnectionString("Default");
            services.RegisterApplicationServices(args);
        });
    })

WeihanLi avatar Jun 12 '22 07:06 WeihanLi

@WeihanLi How can we access parsed arguments in your example in .ConfigureServices()?

VictorioBerra avatar Apr 17 '23 20:04 VictorioBerra