Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions src/System.CommandLine.Hosting/HostingExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ public static class HostingExtensions

public static CommandLineBuilder UseHost(this CommandLineBuilder builder,
Func<string[], IHostBuilder> hostBuilderFactory,
Action<IHostBuilder> configureHost = null) =>
Action<IHostBuilder> configureHost = null,
bool runAsDaemon = false) =>
builder.UseMiddleware(async (invocation, next) =>
{
var argsRemaining = invocation.ParseResult.UnparsedTokens.ToArray();
Expand All @@ -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();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe better using the cancellation token from the invocationContext so that we could graceful stop

}
else
{
await host.StartAsync();
await next(invocation);
await host.StopAsync();
}
});

public static CommandLineBuilder UseHost(this CommandLineBuilder builder,
Action<IHostBuilder> configureHost = null
) => UseHost(builder, null, configureHost);
Action<IHostBuilder> configureHost = null,
bool runAsDaemon = false
) => UseHost(builder, null, configureHost, runAsDaemon);

public static IHostBuilder UseInvocationLifetime(this IHostBuilder host,
InvocationContext invocation, Action<InvocationLifetimeOptions> configureOptions = null)
Expand Down Expand Up @@ -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)
{
Expand Down