Created
June 29, 2021 05:31
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results in the following output:
Followed by a crash as the call to host.Services.GetRequiredService() failed to resolve the registered dependency. :\