Skip to content

Move BindingContext and related types to NamingConventionBinder project#2093

Merged
adamsitnik merged 8 commits intodotnet:mainfrom
adamsitnik:removeServiceProvider
Mar 14, 2023
Merged

Move BindingContext and related types to NamingConventionBinder project#2093
adamsitnik merged 8 commits intodotnet:mainfrom
adamsitnik:removeServiceProvider

Conversation

@adamsitnik
Copy link
Copy Markdown
Member

@adamsitnik adamsitnik commented Mar 14, 2023

In order to remove BindingContext from InvocationContext (a step toward replacing InvocationContext with ParseResult in command handler/action), I've moved it to NamingConventionBinder and made the handler responsible for keeping the reference to BindingContext.

namespace System.CommandLine.NamingConventionBinder
{
    public abstract class BindingHandler : ICommandHandler
    {
        private BindingContext? _bindingContext;

        /// <summary>
        /// The binding context for the current invocation.
        /// </summary>
        public BindingContext GetBindingContext(InvocationContext invocationContext) => _bindingContext ??= new BindingContext(invocationContext);

        public abstract int Invoke(InvocationContext context);

        public abstract Task<int> InvokeAsync(InvocationContext context, CancellationToken cancellationToken = default);
    }
}

Now all the CommandHandler.Create methods return BindingHandler rather than ICommandHandler, and to get the BindingContext the users need to call InvocationContext.GetBindingContext(), which internaly uses ctx.ParseResult.CommandResult.Command.Handler:

public static BindingContext GetBindingContext(this InvocationContext ctx)
{
    return ((BindingHandler)ctx.ParseResult.CommandResult.Command.Handler).GetBindingContext(ctx);
}

Of course it's not that simple, I had to add some workarounds to adjust for the fact that Hosting uses Middleware for dependency injection registration and very late command handler creation.

I know that it ain't pretty, but the only alternative I had was removing NamingConventionBinder project.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants