diff --git a/src/System.CommandLine.Hosting/HostingExtensions.cs b/src/System.CommandLine.Hosting/HostingExtensions.cs index faa10a73c1..22ccb1d1d7 100644 --- a/src/System.CommandLine.Hosting/HostingExtensions.cs +++ b/src/System.CommandLine.Hosting/HostingExtensions.cs @@ -16,7 +16,8 @@ public static class HostingExtensions public static CommandLineBuilder UseHost(this CommandLineBuilder builder, Func hostBuilderFactory, - Action configureHost = null) => + Action configureHost = null, + bool runAsDaemon = false) => builder.UseMiddleware(async (invocation, next) => { var argsRemaining = invocation.ParseResult.UnparsedTokens.ToArray(); @@ -43,16 +44,23 @@ public static CommandLineBuilder UseHost(this CommandLineBuilder builder, invocation.BindingContext.AddService(typeof(IHost), _ => host); - await host.StartAsync(); - - await next(invocation); - - await host.StopAsync(); + if (runAsDaemon) + { + await next(invocation); + await host.RunAsync(); + } + else + { + await host.StartAsync(); + await next(invocation); + await host.StopAsync(); + } }); public static CommandLineBuilder UseHost(this CommandLineBuilder builder, - Action configureHost = null - ) => UseHost(builder, null, configureHost); + Action configureHost = null, + bool runAsDaemon = false + ) => UseHost(builder, null, configureHost, runAsDaemon); public static IHostBuilder UseInvocationLifetime(this IHostBuilder host, InvocationContext invocation, Action configureOptions = null) @@ -101,7 +109,7 @@ public static IHostBuilder UseCommandHandler(this IHostBuilder builder, Type com throw new ArgumentException($"{nameof(handlerType)} must implement {nameof(ICommandHandler)}", nameof(handlerType)); } - if (builder.Properties[typeof(InvocationContext)] is InvocationContext invocation + if (builder.Properties[typeof(InvocationContext)] is InvocationContext invocation && invocation.ParseResult.CommandResult.Command is Command command && command.GetType() == commandType) {