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
5
2
6
- using Microsoft . Extensions . DependencyInjection ;
7
3
using Microsoft . Extensions . Hosting ;
8
- using Microsoft . Extensions . Options ;
9
4
10
5
namespace System . CommandLine . Hosting
11
6
{
12
7
public static class HostingExtensions
13
8
{
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
-
58
9
public static ParseResult GetParseResult ( this IHostBuilder hostBuilder )
59
10
{
60
11
_ = hostBuilder ?? throw new ArgumentNullException ( nameof ( hostBuilder ) ) ;
@@ -76,12 +27,5 @@ public static ParseResult GetParseResult(this HostBuilderContext context)
76
27
77
28
throw new InvalidOperationException ( "Host builder context has no command-line parse result registered to it." ) ;
78
29
}
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
- }
86
30
}
87
31
}
0 commit comments