Back to results for “Generic Host”
.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?

Advanced

Answer

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.

Common follow-ups: What's the risk of resolving services directly from host.Services outside the normal DI injection flow?;How does this differ from a purely interactive console app with no hosted services at all?