Skip to content

Move BindingContext and related types to NamingConventionBinder project #2093

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Mar 14, 2023

Conversation

adamsitnik
Copy link
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