Skip to content

Instantly share code, notes, and snippets.

@brporter
Created June 29, 2021 05:31
Show Gist options
  • Select an option

  • Save brporter/3bf139fc06c0dcccaec312a42d517eb1 to your computer and use it in GitHub Desktop.

Select an option

Save brporter/3bf139fc06c0dcccaec312a42d517eb1 to your computer and use it in GitHub Desktop.
Attempting to configure services in the DI container based on command line parameters with System.CommandLine... and failing miserably
namespace test {
interface IFooBar
{
public string Foo { get; init; }
public int Bar { get; init; }
}
public class FooBar
: IFooBar
{
public FooBar(string f, int b)
{
Foo = f;
Bar = b;
}
public string Foo { get; init; }
public int Bar { get; init; }
}
class Program
{
private class SomeOptions
{
public string Foo { get; set; }
public int Bar { get; set; }
}
static async Task<int> Main(string[] args)
{
var root =
new RootCommand("Foo bar")
{
new Option<string>(
new[] {"-f", "--foo"},
description: "foo"
) {IsRequired = true},
new Option<int>(
new[] {"-b", "--bar"},
description: "bar"
) {IsRequired = true}
};
root.Handler = CommandHandler.Create<IHost>(host =>
{
var opts = host.Services.GetRequiredService<IOptions<SomeOptions>>();
Console.WriteLine($"opts: {opts.Value.Bar} - {opts.Value.Foo}");
var foo = host.Services.GetRequiredService<IFooBar>();
Console.WriteLine($"foo: {foo.Bar} - {foo.Foo}");
// var f = host.Services.GetRequiredService<IFooBar>();
// Console.WriteLine($"{f.Bar} - {f.Foo}");
});
var parser = new CommandLineBuilder(
root
)
.UseHost(host =>
{
host.ConfigureServices(services =>
{
services.AddOptions<SomeOptions>().BindCommandLine().Configure<ParseResult>((o, r) =>
{
Console.WriteLine("Configuring...");
services.AddSingleton<IFooBar>(new FooBar(o.Foo, o.Bar));
});
});
})
.Build();
return await parser.InvokeAsync(args);
}
}
}
@brporter
Copy link
Author

Results in the following output:

Configuring...
opts: 1234 - hello

Followed by a crash as the call to host.Services.GetRequiredService() failed to resolve the registered dependency. :\

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