Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get .NET Core Worker Service CommandLineConfigurationProvider Arguments

Tags:

.net-core

I creating a .NET Core Worker Service app and need to get the Command-Line arguments passed into the app. I can see the arguments while debugging via the IConfiguration configuration > Providers > CommandLineConfigurationProvider, but don't know how to code it to get the arguments.

Any help is appreciated.

like image 799
Shaggy Avatar asked Nov 06 '25 18:11

Shaggy


1 Answers

If you have an object config that provides IConfiguration you simply use config.GetValue<string>("myvaluename").

For example:

public static IHostBuilder CreateHostBuilder(string[] args)
{
    return new HostBuilder()
        .ConfigureAppConfiguration((context, cfg) =>
        {
            cfg.AddCommandLine(args);
        });
}

To get the config:

static void Main(string[] args)
{
    using var host = CreateHostBuilder(args).Build();
    var config = host.Services.GetRequiredService<IConfiguration>();
    var myvalue = config.GetValue<string>("myvalue");
    // .... myvalue may be null if not specified
}

Finally, you invoke your program like this:

myprogram.exe --myvalue abcd

The CommandLineConfigurationProvider is pretty basic, so it doesn't support complex patterns like binary options (present/not present), etc.

like image 74
Guillermo Prandi Avatar answered Nov 09 '25 08:11

Guillermo Prandi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!