Skip to content
This repository has been archived by the owner on Nov 3, 2022. It is now read-only.

agc93/spectre.cli.extensions.dependencyinjection

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

36 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Spectre.Cli.Extensions.DependencyInjection

This package is currently unmaintained! We strongly recommend upgrading to this excellent fork from @devlead! It has been updated to support the newer versions of the library and should be an easy migration for current users of this library.

A type provider for the CLI component of Spectre.Console using the Microsoft.Extensions.DependencyInjection container.

Getting started

Once you've installed both Spectre.Console 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 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);

Using the container

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 git-profile-manager.