Loading

Hosted app quick start

Use Nullean.Argh.Hosting when your app is built on Microsoft.Extensions.Hosting and you want commands and middleware registered in DI with lifetimes and CancellationToken linked to the host.

  1. Add the package reference

    <ItemGroup>
      <PackageReference Include="Nullean.Argh.Hosting" />
    </ItemGroup>
    		
  2. Create a hosted CLI

    using Microsoft.Extensions.Hosting;
    using Nullean.Argh.Hosting;
    
    var builder = Host.CreateApplicationBuilder(args);
    
    builder.Services.AddArgh(args, b =>
    {
        b.Map("hello", MyHandlers.SayHello);
    });
    
    await builder.Build().RunAsync();
    		

    AddArgh mirrors the same Map / Map<T> / UseGlobalOptions / UseNamespaceOptions / UseMiddleware / MapNamespace surface as ArghApp.

  3. Run it

    dotnet run -- hello
    		

The hosting builder adds APIs for controlling DI lifetimes:

using Microsoft.Extensions.DependencyInjection;

builder.Services.AddArgh(args, b =>
{
    b.MapScoped<DeployCommands>();
    b.UseMiddleware<AuditMiddleware>(ServiceLifetime.Singleton);
    b.Map("ping", PingHandlers.Run);
    b.UseGlobalOptions<GlobalOptions>();
});
		
  1. Resolved per command invocation.
  2. Single instance for the process.
  3. Static method - no DI lifetime needed.

AddArgh registers a hosted service that runs ArghRuntime.RunAsync(args) and then calls Environment.Exit with the exit code. The host does not continue after the CLI completes.

Tip

Register AddArgh before other IHostedService registrations if you want the CLI (including --help) to run first and exit without starting later background work.

With hosting, CancellationToken on command handlers is linked to both Ctrl+C and IHostApplicationLifetime.ApplicationStopping.

This means the token also cancels when the host is shutting down, giving your handlers a unified cancellation signal.