dotnet / dotnet/command-line-api

Custom binder with static types

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

Description

According to [these docs](https://docs.microsoft.com/en-us/dotnet/standard/commandline/model-binding), you may implement a custom binder as the following:

```csharp
public class Person
{
public string? Name {set; get;}
}

public class PersonBinder : BinderBase
{
private readonly Option _nameOption;

public PersonBinder(Option nameOption)
{ _nameOption = nameOption; }

protected override Person GetBoundValue(BindingContext context) =>
new Person { Name = context.ParseResult.GetValueForOption(_nameOption) };
}

static async Task Main(string[] args)
{
var nameOption = new Option("--name");
var rootCommand = new RootCommand();
rootCommand.Add(nameOption);
rootCommand.SetHandler((person) =>
{ DoRootCommand(person); },
new PersonBinder(nameOption));
await rootCommand.InvokeAsync(args);
}

public static void DoRootCommand(Person person)
{ Console.WriteLine($"Person = {person?.Name}"); }
```

I wonder how would you modify the `PersonBinder` to work with `static class Person`?

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.