Sdílet prostřednictvím


Generátor zdroje konfigurace

Počínaje rozhraním .NET 8 byl zaveden generátor zdroje konfigurační vazby, který zachycuje konkrétní lokality volání a generuje jejich funkce. Tato funkce poskytuje nativní průběžný (AOT) a ořezávací způsob použití pořadače konfigurace bez použití implementace založené na reflexi. Reflexe vyžaduje dynamické generování kódu, které se nepodporuje ve scénářích AOT.

Tato funkce je možná s nástupem průsečíků jazyka C#, které byly zavedeny v jazyce C# 12. Průsečíky umožňují kompilátoru generovat zdrojový kód, který zachycuje konkrétní volání a nahrazuje je vygenerovaným kódem.

Povolení generátoru zdroje konfigurace

Pokud chcete povolit generátor zdroje konfigurace, přidejte do souboru projektu následující vlastnost:

<PropertyGroup>
    <EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
</PropertyGroup>

Pokud je povolený generátor zdroje konfigurace, kompilátor vygeneruje zdrojový soubor, který obsahuje kód vazby konfigurace. Vygenerovaný zdroj zachycuje rozhraní API vazby z následujících tříd:

Jinými slovy, všechna rozhraní API, která nakonec volají do těchto různých metod vazeb, se zachytí a nahradí vygenerovaným kódem.

Příklad využití

Zvažte konzolovou aplikaci .NET nakonfigurovanou tak, aby se publikovala jako nativní aplikace AOT. Následující kód ukazuje použití generátoru zdroje konfigurace k vytvoření vazby nastavení konfigurace:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <RootNamespace>console_binder_gen</RootNamespace>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <PublishAot>true</PublishAot>
    <InvariantGlobalization>true</InvariantGlobalization>
    <EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.1" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="9.0.1" />
  </ItemGroup>

</Project>

Předchozí soubor projektu umožňuje generátor zdrojů konfigurace nastavením EnableConfigurationBindingGenerator vlastnosti na true.

Dále zvažte soubor Program.cs :

using Microsoft.Extensions.Configuration;

var builder = new ConfigurationBuilder()
    .AddInMemoryCollection(initialData: [
            new("port", "5001"),
            new("enabled", "true"),
            new("apiUrl", "https://jsonplaceholder.typicode.com/")
        ]);

var configuration = builder.Build();

var settings = new Settings();
configuration.Bind(settings);

// Write the values to the console.
Console.WriteLine($"Port = {settings.Port}");
Console.WriteLine($"Enabled = {settings.Enabled}");
Console.WriteLine($"API URL = {settings.ApiUrl}");

class Settings
{
    public int Port { get; set; }
    public bool Enabled { get; set; }
    public string? ApiUrl { get; set; }
}

// This will output the following:
//   Port = 5001
//   Enabled = True
//   API URL = https://jsonplaceholder.typicode.com/

Předchozí kód:

  • Vytvoří instanci tvůrce konfigurace.
  • Volání AddInMemoryCollection a definice tří zdrojových hodnot konfigurace.
  • Volání Build() pro sestavení konfigurace
  • Používá metodu ConfigurationBinder.Bind k vytvoření vazby objektu Settings na konfigurační hodnoty.

Při vytváření aplikace zachytí generátor zdroje konfigurace volání Bind a vygeneruje kód vazby.

Důležité

PublishAot Pokud je vlastnost nastavena na true (nebo jsou povolena jiná upozornění AOT) a EnabledConfigurationBindingGenerator vlastnost je nastavena na false, upozornění IL2026 je vyvolána. Toto upozornění indikuje, že členové jsou při oříznutí atributu RequiresUnreferencedCode může přerušit. Další informace najdete v článku IL2026.

Prozkoumání zdrojového vygenerovaného kódu

Následující kód vygeneruje generátor zdroje konfigurace pro předchozí příklad:

// <auto-generated/>

#nullable enable annotations
#nullable disable warnings

// Suppress warnings about [Obsolete] member usage in generated code.
#pragma warning disable CS0612, CS0618

namespace System.Runtime.CompilerServices
{
    using System;
    using System.CodeDom.Compiler;

    [GeneratedCode("Microsoft.Extensions.Configuration.Binder.SourceGeneration", "9.0.10.47305")]
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
    file sealed class InterceptsLocationAttribute : Attribute
    {
        public InterceptsLocationAttribute(int version, string data)
        {
        }
    }
}

namespace Microsoft.Extensions.Configuration.Binder.SourceGeneration
{
    using Microsoft.Extensions.Configuration;
    using System;
    using System.CodeDom.Compiler;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Runtime.CompilerServices;

    [GeneratedCode("Microsoft.Extensions.Configuration.Binder.SourceGeneration", "9.0.10.47305")]
    file static class BindingExtensions
    {
        #region IConfiguration extensions.
        /// <summary>Attempts to bind the given object instance to configuration values by matching property names against configuration keys recursively.</summary>
        [InterceptsLocation(1, "uDIs2gDFz/yEvxOzjNK4jnIBAABQcm9ncmFtLmNz")] // D:\source\WorkerService1\WorkerService1\Program.cs(13,15)
        public static void Bind_Settings(this IConfiguration configuration, object? instance)
        {
            ArgumentNullException.ThrowIfNull(configuration);

            if (instance is null)
            {
                return;
            }

            var typedObj = (global::Settings)instance;
            BindCore(configuration, ref typedObj, defaultValueIfNotFound: false, binderOptions: null);
        }
        #endregion IConfiguration extensions.

        #region Core binding extensions.
        private readonly static Lazy<HashSet<string>> s_configKeys_Settings = new(() => new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Port", "Enabled", "ApiUrl" });

        public static void BindCore(IConfiguration configuration, ref global::Settings instance, bool defaultValueIfNotFound, BinderOptions? binderOptions)
        {
            ValidateConfigurationKeys(typeof(global::Settings), s_configKeys_Settings, configuration, binderOptions);

            if (configuration["Port"] is string value0 && !string.IsNullOrEmpty(value0))
            {
                instance.Port = ParseInt(value0, configuration.GetSection("Port").Path);
            }
            else if (defaultValueIfNotFound)
            {
                instance.Port = instance.Port;
            }

            if (configuration["Enabled"] is string value1 && !string.IsNullOrEmpty(value1))
            {
                instance.Enabled = ParseBool(value1, configuration.GetSection("Enabled").Path);
            }
            else if (defaultValueIfNotFound)
            {
                instance.Enabled = instance.Enabled;
            }

            if (configuration["ApiUrl"] is string value2)
            {
                instance.ApiUrl = value2;
            }
            else if (defaultValueIfNotFound)
            {
                var currentValue = instance.ApiUrl;
                if (currentValue is not null)
                {
                    instance.ApiUrl = currentValue;
                }
            }
        }


        /// <summary>If required by the binder options, validates that there are no unknown keys in the input configuration object.</summary>
        public static void ValidateConfigurationKeys(Type type, Lazy<HashSet<string>> keys, IConfiguration configuration, BinderOptions? binderOptions)
        {
            if (binderOptions?.ErrorOnUnknownConfiguration is true)
            {
                List<string>? temp = null;
        
                foreach (IConfigurationSection section in configuration.GetChildren())
                {
                    if (!keys.Value.Contains(section.Key))
                    {
                        (temp ??= new List<string>()).Add($"'{section.Key}'");
                    }
                }
        
                if (temp is not null)
                {
                    throw new InvalidOperationException($"'ErrorOnUnknownConfiguration' was set on the provided BinderOptions, but the following properties were not found on the instance of {type}: {string.Join(", ", temp)}");
                }
            }
        }

        public static int ParseInt(string value, string? path)
        {
            try
            {
                return int.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture);
            }
            catch (Exception exception)
            {
                throw new InvalidOperationException($"Failed to convert configuration value at '{path}' to type '{typeof(int)}'.", exception);
            }
        }

        public static bool ParseBool(string value, string? path)
        {
            try
            {
                return bool.Parse(value);
            }
            catch (Exception exception)
            {
                throw new InvalidOperationException($"Failed to convert configuration value at '{path}' to type '{typeof(bool)}'.", exception);
            }
        }
        #endregion Core binding extensions.
    }
}

Poznámka:

Tento vygenerovaný kód se může změnit na základě verze generátoru zdroje konfigurace.

Vygenerovaný kód obsahuje BindingExtensions třídu, která obsahuje metodu BindCore , která provádí skutečnou vazbu. Metoda Bind_Settings volá metodu BindCore a přetypuje instanci na zadaný typ.

Pokud chcete zobrazit vygenerovaný kód, nastavte ho <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> v souboru projektu. Tím zajistíte, že budou soubory viditelné pro vývojáře pro kontrolu. Vygenerovaný kód můžete zobrazit také v Průzkumník řešení sady Visual Studio pod uzlem Microsoft.Extensions.Configuration.Binder.SourceGeneration v projektu>>.

Viz také