dotnet / dotnet/command-line-api

What pattern do you expect for setting handlers?

Open
#1,646 2 comments 1 reaction 0 assignees View on GitHub
question
Dominant language
C#
Stars
3.7k
Forks
428
PR merge metrics
No merged PRs in 30d

Description

Apologies for this vague question, but as the documentation isn't finished I can't find a clear answer to know if I'm doing this "right".

I've created a class for each of my handlers, as my app has a lot of options, and I've made each of the handlers an ICommandHandler, then creating my commands as such:

var anOption = new Option(new[] { "--option", "-o" }, "Description");

Command cmd = new("sub-command", "Sub command description")
{
anOption
};

var binder = new SubCommandBinder(anOption);

cmd.SetHandler((SubCommandOptions options, InvocationContext ctx, CancellationToken ct) =>
{
var handler = new SubCommandHandler(options, ct);
return handler.InvokeAsync(ctx);
}, binder);

return cmd;

And the binder is just defined as in the beta 2 announcement. Is this the way you expect people to invoke the commands? How would I go about using dependency injection in this approach? The beta 2 announcement shows creating a MyCustomBinder as an example, but I'm not really sure I understand this approach - is it expected that dependencies will be handled by the binder, or to use the InvocationContext within the InvokeAsync method?

At the moment I'm injecting an IHost into the class where I create my RootCommand, then just passing that into my handler constructors, and this appears to work - is this your intention?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.