Strategies for Dependency Injection in CommandSettings for Enhanced Argument Handling #1376
Unanswered
andreasciamanna
asked this question in
Q&A
Replies: 1 comment 6 replies
-
Are you using the standard DI pattern, or .NET Generic Host? |
Beta Was this translation helpful? Give feedback.
6 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Context:
I'm working with commands that have optional arguments, specifically "source" and "target" branches of the local repository in the directory where the command is executed. When these arguments are omitted, their values are inferred using injected service classes. This inference includes identifying the current local branch as a "source" or fetching the default branch from an API based on the repository host (e.g., GitHub, GitLab, etc.). As this logic is crucial, an exception is thrown if a branch cannot be detected. These optional parameters are used by more than one command.
The Problem:
The logic to infer these parameters is repeated across each command that requires the optional(ish) parameters, leading to code duplication. While I have reduced this duplication by creating helper methods, it has not been completely eliminated.
Proposed Solution:
I propose moving this inference logic to the class extending
CommandSettings
.Ideally, this logic would run before the interceptor class is triggered, allowing for programmatic changes in the settings' values or throwing an exception if the program cannot infer values for these arguments.
It would streamline the process by placing the logic in a more suitable location within the flow, particularly within the settings validation method (since there isn't a sanitation method, which would be probably more suited to this scope).
Challenges Faced:
It appears that DI can't be used on classes extending
CommandSettings
.When attempting to use DI in the settings class, I encounter a
CommandRuntimeException
due to the absence of a parameterless constructor in the settings class. Here's the specific exception encountered:I am exploring whether this is a feature currently unsupported by
spectre.console
or if there's an existing way to achieve this that I might be overlooking.Having recently returned to C#/.NET development after a decade with other languages, I am eager to learn about any new practices or patterns that I might have missed.
Any guidance, suggestions, or insights would be greatly appreciated in helping to enhance argument handling in this context.
Thanks,
Andrea
Beta Was this translation helpful? Give feedback.
All reactions