Dependency injection
When using Nullean.Argh.Hosting, DI integration is fully transparent. Register your handler and middleware types in the service collection and the generated code resolves them automatically. No manual ServiceProvider wiring needed.
public class DeployCommands(IDeployService deployer)
{
public async Task<int> Run(string environment)
{
await deployer.DeployAsync(environment);
return 0;
}
}
builder.Services.AddScoped<IDeployService, DeployService>();
builder.Services.AddArgh(args, b => b.Map<DeployCommands>());
- The service must be registered in the DI container
- Handler type is registered and its public methods become commands
| API | Purpose |
|---|---|
Map<T>() |
Register T as transient and add all its public methods as commands. |
MapTransient<T>() / MapScoped<T>() / MapSingleton<T>() |
Same, with an explicit DI lifetime. |
UseGlobalOptions<T>() |
Register T as the global options type and add it to DI. |
UseMiddleware<TMiddleware>() |
Register middleware as transient. |
UseMiddleware<TMiddleware>(lifetime) |
Register middleware with an explicit DI lifetime. |
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>();
});
- Resolved per command invocation
- Single instance for the process
- Static method - no DI lifetime needed
Advanced: using DI without Nullean.Argh.Hosting
For advanced use or when not using Nullean.Argh.Hosting: ArghServices.ServiceProvider is typed as System.IServiceProvider and set when running under a host.
For Map<T>() instance methods and UseMiddleware<T>() / [MiddlewareAttribute<T>], generated code resolves via GetService(typeof(T)) when a provider is present. Otherwise it falls back to new T().
Warning
For native AOT / trimming, register handler and middleware types explicitly in DI so required constructors are preserved.