dotnet / dotnet/command-line-api

Dependency Inject / Hosting / Middleware

Open
#1,025 14 comments 0 reactions 0 assignees View on GitHub
Area-Parser and Binder needs discussion
Dominant language
C#
Stars
3.7k
Forks
428
PR merge metrics
No merged PRs in 30d

Description

Currently there is a lot of disparate discussion around utilizing dependency injects, hosting, and middleware. This issue aims to consolidate that discussion.

@jonsequitur, @KathleenDollard, and @Keboo met and after some discussion wanted to get more feedback on potential directions.

## Current process
For a command line invocation the process flows through several steps:

Tokenization -> Parsing -> Middleware invocation -> Model binding -> Command handler invocation

Inside of the Middleware invocation various steps occur. Though the order is configurable the following is the current default order:
```C#
internal enum MiddlewareOrderInternal
{
Startup = -4000,
ExceptionHandler = -3000,
EnvironmentVariableDirective = -2600,
ConfigureConsole = -2500,
RegisterWithDotnetSuggest = -2400,
DebugDirective = -2300,
ParseDirective = -2200,
SuggestDirective = -2000,
TypoCorrection = -1900,
VersionOption = -1200,
HelpOption = -1100,
ParseErrorReporting = 1000,
}
```

Within all of these steps, there are various places where dependency injection may be desirable:
- Manual handling of dependency inject within your code. Nothing is handled by this library and all DI registration and resolution occur within your code.
- Within the command handler invocation, such as specifying a service as a parameter in the invocation handler.
- Within custom individual middleware steps.

## Considerations
- The earlier in the process that dependency injection containers are configured may incur additional performance hits; even when the dependency are not consumed.

- Dependency injection container creation may be fragile. This can cause startup exceptions if it is configured incorrectly. At the same time it is common to want to use dependency such as logger, built from the dependency injection container. This can cause circular dependencies.

- We consider the process of spinning up a hosting model (such as generic host) a similar problem to creating a dependency injection container. A primary purpose of many hosting models is to provide the mechanism for the DI container to resolve dependencies.

## Requested feedback
- Is the above list of places where dependency injection might be desirable complete?
- Are there any other use cases around dependency injection or hosting that don't appear to be addressed?
- Is providing host/dependency injection container creation as a middleware step sufficient?

Related Items:
#671
#918
#919
#974

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.