Inject CommandSettings or retrieve during/after run #640
Replies: 2 comments 8 replies
-
@woutervanranst I'm not sure I get what you're aiming at. Are you trying to use the |
Beta Was this translation helpful? Give feedback.
-
@woutervanranst I had an idea today: I tested this using the following code: using Spectre.Console;
using Spectre.Console.Cli;
// build DI
var container = new SimpleInjector.Container();
var settingsInstance = new HelloCommand.Settings();
AnsiConsole.MarkupLine($"[gray]name before run: {settingsInstance.Name}[/]");
// register settings as instance.
container.RegisterInstance(typeof(HelloCommand.Settings), settingsInstance);
// run command
var app = new CommandApp<HelloCommand>(new SimpleInjectorRegistrar(container));
var result = app.Run(args);
// resolve settings again
var settings = (HelloCommand.Settings)container.GetInstance(typeof(HelloCommand.Settings));
AnsiConsole.MarkupLine($"[yellow]name after command-run: {settings.Name}[/]");
return result;
internal sealed class HelloCommand : Command<HelloCommand.Settings>
{
public sealed class Settings : CommandSettings
{
[CommandOption("-n|--name")] public string Name { get; set; } = "Unknown";
}
public override int Execute(CommandContext context, Settings settings)
{
AnsiConsole.MarkupLine($"[gray]name inside command: {settings.Name}[/]");
return 0;
}
} I'm using SimpleInjector here for DI, so your code might look a bit different for registering/retrieving. |
Beta Was this translation helpful? Give feedback.
-
Use case (simplified):
CommandSettings
are not available through dependency injection - hence I cannot have this client injected and must manually instantiate it inExecute(CommandContext ctx, CommandSettings settings) {}
which defeats the purpose of DI somewhaatWould there be an easy/elegant way to inject the parsed
CommandSettings
?I feel something may be possible with an
ICommandInterceptor
and/orITypeRegistrar.RegisterLazy
(deferring the resolution until the command is fully parsed)?Alternatively, is there a way where I could get the parsed
CommandSettings
afterCommandApp.Run(args)
? In that case I would set up a secondServiceCollection
with the parsedCommandSettings
, the container client, ... and go from there.Beta Was this translation helpful? Give feedback.
All reactions