dotnet / dotnet/command-line-api
Suggestion: try to resolve `ICommandHandler` when no handler registered
- Dominant language
- C#
- Stars
- 3.7k
- Forks
- 428
- PR merge metrics
- No merged PRs in 30d
Description
When there's no handler set, maybe we could try to resolve `ICommandHandler`, if there's it could be used as the command handler.
For example:
``` c#
var command = new Command("test");
command.SetHandler(invocationContext => invocationContext.GetHost()
.Services.GetRequiredService()
.InvokeAsync(invocationContext));
await new CommandLineBuilder(command)
.UseHost(hostBuilder =>
{
hostBuilder.ConfigureServices(services =>
{
services.AddSingleton();
});
})
.Build()
.InvokeAsync(args);
```
When there's `ICommandHandler` registerd, I think we could try to resolve the command handler, so that it will like follows:
``` c#
var command = new Command("test");
await new CommandLineBuilder(command)
.UseHost(hostBuilder =>
{
hostBuilder.ConfigureServices(services =>
{
services.AddSingleton();
});
})
.Build()
.InvokeAsync(args);
```
This may make it more simple to use
Possible implement, maybe a middleware like follows:
``` c#
.AddMiddleware(invocationContext =>
{
var serviceProvider =
invocationContext.BindingContext.GetService()?.Services ?? // only when using the hosting extensions
invocationContext.BindingContext;
var commandHandler = serviceProvider.GetService();
if (command.Handler is null && commandHandler != null)
{
command.Handler = commandHandler;
}
})
```
Usage example: https://github.com/WeihanLi/dotnet-exec/blob/bc3bf2a71bdc9a024c25857c45cfa44faa3a4742/src/dotnet-exec/Program.cs#L8
Contributor guide
Assessment
This issue has not been assessed yet.