command-line-api icon indicating copy to clipboard operation
command-line-api copied to clipboard

Suggestion: try to resolve `ICommandHandler` when no handler registered

Open WeihanLi opened this issue 3 years ago • 0 comments

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:

var command = new Command("test");

command.SetHandler(invocationContext => invocationContext.GetHost()
    .Services.GetRequiredService<ICommandHandler>()
    .InvokeAsync(invocationContext));

await new CommandLineBuilder(command)
    .UseHost(hostBuilder =>
    {
        hostBuilder.ConfigureServices(services =>
        {
            services.AddSingleton<ICommandHandler, CommandHandler>();
        });
    })
    .Build()
    .InvokeAsync(args);

When there's ICommandHandler registerd, I think we could try to resolve the command handler, so that it will like follows:

var command = new Command("test");
await new CommandLineBuilder(command)
    .UseHost(hostBuilder =>
    {
        hostBuilder.ConfigureServices(services =>
        {
            services.AddSingleton<ICommandHandler, CommandHandler>();
        });
    })
    .Build()
    .InvokeAsync(args);

This may make it more simple to use

Possible implement, maybe a middleware like follows:

    .AddMiddleware(invocationContext =>
    {
        var serviceProvider = 
                invocationContext.BindingContext.GetService<IHost>()?.Services ?? // only when using the hosting extensions
                invocationContext.BindingContext;
        var commandHandler = serviceProvider.GetService<ICommandHandler>();
        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

WeihanLi avatar Jun 12 '22 14:06 WeihanLi