Skip to content

Dependency Injection

Matthias Beerens edited this page Apr 11, 2021 · 5 revisions

Use a DI/IoC container

The library has a constructor overload to take in an instance of IServiceCollection. The library will add any missing required service to this collection and construct an IServiceProvider for internal use.

This allows you to override any internal service with your own implementation.

You can inject services in your own Command's constructor.

Example

public static void Main(string[] args)
{
    var options = new CommandLineParserOptions
    {
        AppName = "CLI.Tutorial",
    };

    var services = new ServiceCollection();

    // register our own service that will be injected
    services.AddScoped<ICustomInjectedService, CustomInjectedService>();

    // register the command line parser
    services.AddCommandLineParser<OptionModel>(options);

    // Build service provider
    var provider = services.BuildServiceProvider();

    // Resolve parser
    var parser = provider.GetRequiredService<ICommandLineParser<OptionModel>>()

    // Register the command
    parser.RegisterCommand<StartServerCommand>()

    // Use the parser as normal.. 
    var result = parser.Parse(args);
}

Command

public class StartServerCommand : Command
{
    private readonly ICustomInjectedService customService;

    public CommandWithInjectedServices(ICustomInjectedService customService)
    {
        this.customService = customService ?? throw new ArgumentNullException(nameof(customService));
    }

    public override void OnConfigure(ICommandConfigurationBuilder builder)
    {
        builder.Name("di");
    }

    public override void OnExecute()
    {
        customService.DoSomething();
    }
}
Clone this wiki locally