Option fallback - adambajguz/Typin GitHub Wiki

An option can be configured to use the value of a variable from IOptionFallbackProvider as a fallback. If the value for such an option is not directly specified in the arguments, it will be extracted using IOptionFallbackProvider instead.

By default EnvironmentVariableFallbackProvider is used as a option fallback values provider. It internally uses IEnvironmentVariablesAccessor to access environment variables' values (read more). However EmptyFallbackProvider can be used to disable fallback or a custom implementation of IOptionFallbackProvider interface with user-defined lifetime can be used:

    builder.UseOptionFallbackProvider<EmptyFallbackProvider>(lifetime = ServiceLifetime.Singleton);

Here's an example of a required option that can be either provided directly or extracted from the environment:

[Command]
public class AuthCommand : ICommand
{
    [CommandOption("token", IsRequired = true, FallbackVariableName = "AUTH_TOKEN")]
    public string AuthToken { get; set; }

    public ValueTask ExecuteAsync(IConsole console)
    {
        console.Output.WriteLine(AuthToken);

        return default;
    }
}
> $env:AUTH_TOKEN="test"

> myapp.exe

test

IOptionFallbackProvider variables can be used as fallback for options of enumerable types too. In this case, the value of the variable will be split by Path.PathSeparator (which is ; on Windows, : on Linux). This also ensures direct compatiblity when environment variables.