.NET › Generic Host
How would you build a console application that supports both interactive command execution and long-running hosted service behavior using the Generic Host?
AdvancedAnswer
You can register both regular services and one or more IHostedService/BackgroundService implementations on the same host, with hosted services starting automatically on host.Run() (or host.RunAsync()) while other services remain available for on-demand use -- for genuinely interactive CLI tools, host.RunAsync() combined with manual coordination (like waiting on a specific hosted service's completion, or using host.Services.GetRequiredService<T>() to resolve and invoke command-handling logic directly before or instead of running the full host lifecycle) lets you blend both patterns as needed.
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddSingleton<ICommandProcessor, CommandProcessor>();
builder.Services.AddHostedService<BackgroundSyncService>();
var host = builder.Build();
// Resolve and use a service directly for one-off interactive logic
var processor = host.Services.GetRequiredService<ICommandProcessor>();
await processor.ProcessAsync(args);
// Then run the host for its long-running hosted services
await host.RunAsync();Real-world example A hybrid CLI/daemon tool processes an immediate command-line argument interactively via a resolved service, then transitions into running as a long-lived background sync daemon using the same Generic Host infrastructure for both modes.