Skip to content

[API Proposal]: The Configuration Binding Generator should be able to understand different common formats of boolean values #117589

@baronfel

Description

@baronfel

Background and motivation

Today the Source-Generated Configuration binding supports only values that satisfy bool.Parse - but especially in the space of environment variables and user-facing config files there are many formats that are quite common:

  • 1 / 0
  • y / n
  • yes / no

The dotnet CLI has broad support for these in its current hand-rolled configuration/env var handling, but we're investigating unifying on IConfiguration (and binding generation) as part of an overall road to AOT and this would be an unfortunate take-back for us. I'm sure we could hand-roll something while still being based on IConfiguration, but the generator is such a nice thing to reach for!

API Proposal

There should be some way to signal on a field/property basis that a boolean field/property supports more than just true/false as signal values - perhaps an attribute, or some way to 'tag' the field/property with a converter like JSON Source Generation can do.

API Usage

/// <summary>
/// Configuration settings that control the CLI's user interface and interaction behavior.
/// </summary>
public sealed class CliUserExperienceConfiguration
{
    /// <summary>
    /// Gets or sets whether telemetry collection is disabled.
    /// Mapped from DOTNET_CLI_TELEMETRY_OPTOUT environment variable.
    /// </summary>
    [BooleanBinding(AllowedForms = Boolean.TrueFalse | Boolean.YesNo | Boolean.ZeroOne)]
    public bool TelemetryOptOut { get; set; } = CompileOptions.TelemetryOptOutDefault;

    /// <summary>
    /// Gets or sets whether to suppress the .NET logo on startup.
    /// Mapped from DOTNET_NOLOGO environment variable.
    /// </summary>
    [BooleanBinding(AllowedForms = Boolean.TrueFalse | Boolean.YesNo | Boolean.ZeroOne)]
    public bool NoLogo { get; set; } = false;

    /// <summary>
    /// Gets or sets whether to force UTF-8 encoding for console output.
    /// Mapped from DOTNET_CLI_FORCE_UTF8_ENCODING environment variable.
    /// </summary>
    [BooleanBinding(AllowedForms = Boolean.TrueFalse | Boolean.YesNo | Boolean.ZeroOne)]
    public bool ForceUtf8Encoding { get; set; } = false;

    ....
}

Alternative Designs

I suppose for our use case specifically we could have a custom type that we completely control the parsing of that could be coercible to bool for usage in the codebase?

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions