A type provider for the CLI component of Spectre.Console
using the Microsoft.Extensions.DependencyInjection
container.
This is a fork of agc93/spectre.cli.extensions.dependencyinjection to support newer versions of Spectre.Console.Cli
Once you've installed both Spectre.Console.Cli
and this package, just change the call to new CommandApp()
in your Program.cs
to match the below:
var services = new ServiceCollection();
// add extra services to the container here
using var registrar = new DependencyInjectionRegistrar(services);
var app = new CommandApp(registrar);
app.Configure(config =>
{
// configure your commands as per usual
// commands are automatically added to the container
}
return app.Run(args);
Once you've changed your Program.cs
as above, you can inject anything you need into your commands:
// Program.cs
var services = new ServiceCollection();
services.AddSingleton<ICoolService, MyCoolService>();
using registrar = new DependencyInjectionRegistrar(services);
var app = new CommandApp(registrar);
app.Configure(config =>
{
config.AddCommand<SomeCommand>("command");
// commands are automatically added to the container
}
// in SomeCommand.cs
public class SomeCommand : Command<SomeCommand.Settings>
{
public ProfileCreateCommand(ICoolService service)
{
// the `ICoolService` parameter will be automatically injected with an instance of `MyCoolService`
}
public override int Execute(SomeCommand.Settings settings, ILookup<string, string> unmapped)
{
// command logic here
}
}
For a more complex example, check out devlead/dpi.