File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed
System.CommandLine.Hosting.Tests
System.CommandLine.Hosting Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change @@ -366,5 +366,46 @@ public static void GetInvocationContext_in_ConfigureServices_throws_if_not_withi
366366 } )
367367 . Should ( ) . Throw < InvalidOperationException > ( ) ;
368368 }
369+
370+ [ Fact ]
371+ public static void GetHost_returns_non_null_instance_in_subsequent_middleware ( )
372+ {
373+ bool hostAsserted = false ;
374+ var parser = new CommandLineBuilder ( )
375+ . UseHost ( )
376+ . UseMiddleware ( ( invCtx , next ) =>
377+ {
378+ IHost host = invCtx . GetHost ( ) ;
379+ host . Should ( ) . NotBeNull ( ) ;
380+ hostAsserted = true ;
381+
382+ return next ( invCtx ) ;
383+ } )
384+ . Build ( ) ;
385+
386+ _ = parser . Invoke ( string . Empty ) ;
387+
388+ hostAsserted . Should ( ) . BeTrue ( ) ;
389+ }
390+
391+ [ Fact ]
392+ public static void GetHost_returns_null_when_no_host_in_invocation ( )
393+ {
394+ bool hostAsserted = false ;
395+ var parser = new CommandLineBuilder ( )
396+ . UseMiddleware ( ( invCtx , next ) =>
397+ {
398+ IHost host = invCtx . GetHost ( ) ;
399+ host . Should ( ) . BeNull ( ) ;
400+ hostAsserted = true ;
401+
402+ return next ( invCtx ) ;
403+ } )
404+ . Build ( ) ;
405+
406+ _ = parser . Invoke ( string . Empty ) ;
407+
408+ hostAsserted . Should ( ) . BeTrue ( ) ;
409+ }
369410 }
370411}
Original file line number Diff line number Diff line change @@ -138,5 +138,12 @@ public static InvocationContext GetInvocationContext(this HostBuilderContext con
138138
139139 throw new InvalidOperationException ( "Host builder has no Invocation Context registered to it." ) ;
140140 }
141+
142+ public static IHost GetHost ( this InvocationContext invocationContext )
143+ {
144+ _ = invocationContext ?? throw new ArgumentNullException ( paramName : nameof ( invocationContext ) ) ;
145+ var hostModelBinder = new ModelBinder < IHost > ( ) ;
146+ return ( IHost ) hostModelBinder . CreateInstance ( invocationContext . BindingContext ) ;
147+ }
141148 }
142149}
You can’t perform that action at this time.
0 commit comments