Skip to content

RFC: Add runAsDaemon option to UseHost #1243

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
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