dotnet / dotnet/command-line-api
How to Prevent `IHost` from Starting on Command-Line
- Dominant language
- C#
- Stars
- 3.7k
- Forks
- 428
- PR merge metrics
- No merged PRs in 30d
Description
How to do you prevent `IHost` from starting when executing a command on the command-line? It starts no matter what when using `UseHost`. What's the best way to allow all `Command` class `ICommandHandler` interfaces to execute without starting the middleware that runs `IHostBuilder.StartAsync`? But still have all the `IHost` objects; example `IConfiguration` available `DI` in the `ICommandHandler` interface?
Running as:
```bash
> myApp.exe run
```
`Program.cs`
---
```csharp
public sealed partial class Program
{
static async Task Main(string[] args)
{
var rootCommand = new DefaultRootCommand();
var parser = new CommandLineBuilder(rootCommand)
.UseHost(DefaultNeoHostBuilderFactory, builder =>
{
builder.ConfigureServices((builder, services) =>
{
services.AddSingleton();
});
builder.UseCommandHandler();
})
.UseDefaults()
.Build();
return await parser.InvokeAsync(args);
}
}
```
`DefaultRootCommand.cs`
---
```csharp
internal sealed class DefaultRootCommand: Command
{
public RunCommand() : base("run")
{
IsHidden = true;
}
public new sealed class Handler : ICommandHandler
{
public Handler(IConfiguration config) // want this from IHost
{
}
public async Task InvokeAsync(InvocationContext context)
{
var host = context.GetHost();
// What code do I write to prevent 'host' from StartAsync
return await RunConsolePrompt(ref context);
}
public int Invoke(InvocationContext context)
{
throw new NotImplementedException();
}
public static Task RunConsolePrompt(ref InvocationContext context)
{
while (true)
{
lock (context.Console.Out)
{
context.Console.Clear();
context.Console.SetTerminalForegroundColor(ConsoleColor.DarkBlue);
context.Console.Write("Prompt> ");
var line = context.Console.ReadLine();
context.Console.ResetTerminalForegroundColor();
return await PromptCommandsInvokeAsync(line);
}
}
}
}
}
```
`Console Output`
---
```bash
Prompt>
[2024-04-21 15:00:32.317] dbug: Microsoft.Extensions.Hosting.Internal.Host[3] Hosting stopping
[2024-04-21 15:00:32.317] dbug: Microsoft.Extensions.Hosting.Internal.Host[4] Hosting stopped
```
Contributor guide
Assessment
This issue has not been assessed yet.