1- using System . CommandLine . Binding ;
2- using System . CommandLine . Invocation ;
3- using System . CommandLine . NamingConventionBinder ;
4- using CommandHandler = System . CommandLine . NamingConventionBinder . CommandHandler ;
1+ #nullable enable
52
6- using Microsoft . Extensions . DependencyInjection ;
73using Microsoft . Extensions . Hosting ;
8- using Microsoft . Extensions . Options ;
94
105namespace System . CommandLine . Hosting
116{
127 public static class HostingExtensions
138 {
14- public static CommandLineConfiguration UseHost (
15- this CommandLineConfiguration config ,
16- Func < string [ ] , IHostBuilder > hostBuilderFactory ,
17- Action < IHostBuilder > configureHost = null )
18- {
19- if ( config . RootCommand is RootCommand root )
20- {
21- root . Add ( new Directive ( HostingAction . HostingDirectiveName ) ) ;
22- }
23-
24- HostingAction . SetHandlers ( config . RootCommand , hostBuilderFactory , configureHost ) ;
25-
26- return config ;
27- }
28-
29- public static CommandLineConfiguration UseHost (
30- this CommandLineConfiguration config ,
31- Action < IHostBuilder > configureHost = null
32- ) => UseHost ( config , null , configureHost ) ;
33-
34- public static OptionsBuilder < TOptions > BindCommandLine < TOptions > (
35- this OptionsBuilder < TOptions > optionsBuilder )
36- where TOptions : class
37- {
38- if ( optionsBuilder is null )
39- throw new ArgumentNullException ( nameof ( optionsBuilder ) ) ;
40- return optionsBuilder . Configure < IServiceProvider > ( ( opts , serviceProvider ) =>
41- {
42- var modelBinder = serviceProvider
43- . GetService < ModelBinder < TOptions > > ( )
44- ?? new ModelBinder < TOptions > ( ) ;
45- var bindingContext = serviceProvider . GetRequiredService < BindingContext > ( ) ;
46- modelBinder . UpdateInstance ( opts , bindingContext ) ;
47- } ) ;
48- }
49-
50- public static Command UseCommandHandler < THandler > ( this Command command )
51- where THandler : CommandLineAction
52- {
53- command . Action = CommandHandler . Create ( typeof ( THandler ) . GetMethod ( nameof ( AsynchronousCommandLineAction . InvokeAsync ) ) ) ;
54-
55- return command ;
56- }
57-
589 public static ParseResult GetParseResult ( this IHostBuilder hostBuilder )
5910 {
6011 _ = hostBuilder ?? throw new ArgumentNullException ( nameof ( hostBuilder ) ) ;
@@ -76,12 +27,5 @@ public static ParseResult GetParseResult(this HostBuilderContext context)
7627
7728 throw new InvalidOperationException ( "Host builder context has no command-line parse result registered to it." ) ;
7829 }
79-
80- public static IHost GetHost ( this ParseResult parseResult )
81- {
82- _ = parseResult ?? throw new ArgumentNullException ( paramName : nameof ( parseResult ) ) ;
83- var hostModelBinder = new ModelBinder < IHost > ( ) ;
84- return ( IHost ) hostModelBinder . CreateInstance ( parseResult . GetBindingContext ( ) ) ;
85- }
8630 }
8731}
0 commit comments