Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
211 changes: 211 additions & 0 deletions docs/core/extensions/configuration-generator.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
---
title: Compile-time configuration source generation
description: Learn how to use the configuration source generator to intercept specific call sites and bypass reflection-based configuration binding.
author: IEvangelist
ms.author: dapine
ms.date: 10/09/2024
---

# Configuration source generator

Starting with .NET 8, a configuration binding source generator was introduced that intercepts specific call sites and generates their functionality. This feature provides a [Native ahead-of-time (AOT)](../deploying/native-aot/index.md) and [trim-friendly](../deploying/trimming/trim-self-contained.md) way to use the [configuration binder](configuration.md#binding), without the use of the reflection-based implementation. Reflection requires dynamic code generation, which isn't supported in AOT scenarios.

This feature is possible with the advent of [C# interceptors](/dotnet/csharp/whats-new/csharp-12#interceptors) that were introduced in C# 12. Interceptors allow the compiler to generate source code that intercepts specific calls and substitutes them with generated code.

## Enable the configuration source generator

To enable the configuration source generator, add the following property to your project file:

```xml
<PropertyGroup>
<EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
</PropertyGroup>
```

When the configuration source generator is enabled, the compiler generates a source file that contains the configuration binding code. The generated source intercepts binding APIs from the following classes:

- <xref:Microsoft.Extensions.Configuration.ConfigurationBinder?displayProperty=fullName>
- <xref:Microsoft.Extensions.DependencyInjection.OptionsBuilderConfigurationExtensions?displayProperty=fullName>
- <xref:Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions?displayProperty=nameWithType>

In other words, all APIs that eventually call into these various binding methods are intercepted and replaced with generated code.

## Example usage

Consider a .NET console application configured to publish as a native AOT app. The following code demonstrates how to use the configuration source generator to bind configuration settings:

:::code language="xml" source="snippets/configuration/console-binder-gen/console-binder-gen.csproj" highlight="9,11":::

The preceding project file enables the configuration source generator by setting the `EnableConfigurationBindingGenerator` property to `true`.

Next, consider the _Program.cs_ file:

:::code source="snippets/configuration/console-binder-gen/Program.cs" highlight="12-14":::

The preceding code:

- Instantiates a configuration builder instance.
- Calls <xref:Microsoft.Extensions.Configuration.MemoryConfigurationBuilderExtensions.AddInMemoryCollection%2A> and defines three configuration source values.
- Calls <xref:Microsoft.Extensions.Configuration.IConfigurationBuilder.Build> to build the configuration.
- Uses the <xref:Microsoft.Extensions.Configuration.ConfigurationBinder.GetValue%2A?displayProperty=nameWithType> extension method to get the value for each configuration key.

When the application is built, the configuration source generator intercepts the call to `GetValue<T>` and generates the binding code.

> [!IMPORTANT]
> When the `PublishAot` property is set to `true` (or any other AOT warnings are enabled) and the `EnabledConfigurationBindingGenerator` property is set to `false`, warning `IL2026` is raised. This warning indicates that members are attributed with [RequiresUnreferencedCode](xref:System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute) may break when trimming. For more information, see [IL2026](/dotnet/core/deploying/trimming/trim-warnings/il2026).

### Explore the source generated code

The following code is generated by the configuration source generator for the preceding example:

```csharp
// <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",
"8.0.10.31311")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
file sealed class InterceptsLocationAttribute : Attribute
{
public InterceptsLocationAttribute(string filePath, int line, int column)
{
}
}
}

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

[GeneratedCode(
"Microsoft.Extensions.Configuration.Binder.SourceGeneration",
"8.0.10.31311")]
file static class BindingExtensions
{
#region IConfiguration extensions.
/// <summary>
/// Extracts the value with the specified key and converts it to the specified type.
/// </summary>
[InterceptsLocation(@"C:\source\configuration\console-binder-gen\Program.cs", 12, 26)]
[InterceptsLocation(@"C:\source\configuration\console-binder-gen\Program.cs", 13, 29)]
[InterceptsLocation(@"C:\source\configuration\console-binder-gen\Program.cs", 14, 28)]
public static T? GetValue<T>(this IConfiguration configuration, string key) =>
(T?)(BindingExtensions.GetValueCore(configuration, typeof(T), key) ?? default(T));
#endregion IConfiguration extensions.

#region Core binding extensions.
public static object? GetValueCore(
this IConfiguration configuration, Type type, string key)
{
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}

IConfigurationSection section = configuration.GetSection(key);

if (section.Value is not string value)
{
return null;
}

if (type == typeof(int))
{
return ParseInt(value, () => section.Path);
}
else if (type == typeof(bool))
{
return ParseBool(value, () => section.Path);
}
else if (type == typeof(global::System.Uri))
{
return ParseSystemUri(value, () => section.Path);
}

return null;
}

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

public static bool ParseBool(
string value, Func<string?> getPath)
{
try
{
return bool.Parse(value);
}
catch (Exception exception)
{
throw new InvalidOperationException(
$"Failed to convert configuration value at " +
"'{getPath()}' to type '{typeof(bool)}'.",
exception);
}
}

public static global::System.Uri ParseSystemUri(
string value, Func<string?> getPath)
{
try
{
return new Uri(
value,
UriKind.RelativeOrAbsolute);
}
catch (Exception exception)
{
throw new InvalidOperationException(
$"Failed to convert configuration value at " +
"'{getPath()}' to type '{typeof(global::System.Uri)}'.",
exception);
}
}
#endregion Core binding extensions.
}
}
```

> [!NOTE]
> This generated code is subject to change based on the version of the configuration source generator.

The generated code contains the `BindingExtensions` class, which contains the `GetValueCore` method that performs the actual binding. The `GetValue<T>` extension method calls the `GetValueCore` method and casts the result to the specified type.

To see the generated code, set the `<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>` in the project file. This ensures that the files are visible to the developer for inspection.

## See also

- [Configuration in .NET](configuration.md)
- [Roslyn: Interceptors feature](https://github.com/dotnet/roslyn/blob/main/docs/features/interceptors.md)
- [Options pattern in .NET](options.md)
6 changes: 4 additions & 2 deletions docs/core/extensions/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ title: Configuration
description: Learn how to use the Configuration API to configure .NET applications. Explore various inbuilt configuration providers.
author: IEvangelist
ms.author: dapine
ms.date: 07/19/2023
ms.date: 10/09/2024
ms.topic: overview
---

Expand Down Expand Up @@ -64,7 +64,9 @@ Adding a configuration provider overrides previous configuration values. For exa

### Binding

One of the key advantages of using the .NET configuration abstractions is the ability to bind configuration values to instances of .NET objects. For example, the JSON configuration provider can be used to map *appsettings.json* files to .NET objects and is used with [dependency injection](dependency-injection.md). This enables the [options pattern](options.md), which uses classes to provide strongly typed access to groups of related settings. .NET configuration provides various abstractions. Consider the following interfaces:
One of the key advantages of using the .NET configuration abstractions is the ability to bind configuration values to instances of .NET objects. For example, the JSON configuration provider can be used to map *appsettings.json* files to .NET objects and is used with [dependency injection](dependency-injection.md). This enables the [options pattern](options.md), which uses classes to provide strongly typed access to groups of related settings. The default binder is reflection-based, but there's a [source generator alternative](configuration-generator.md) that's easy to enable.

.NET configuration provides various abstractions. Consider the following interfaces:

- <xref:Microsoft.Extensions.Configuration.IConfiguration>: Represents a set of key/value application configuration properties.
- <xref:Microsoft.Extensions.Configuration.IConfigurationRoot>: Represents the root of an `IConfiguration` hierarchy.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "options-validation-onstart"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "console-validation-gen", "console-validation-gen\console-validation-gen.csproj", "{D64017C1-B9DD-4FC4-AB1D-62109CF2687C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "console-binder-gen", "console-binder-gen\console-binder-gen.csproj", "{DCB64163-DF91-4EE8-ABE1-D90AE8DCA54B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -171,6 +173,10 @@ Global
{D64017C1-B9DD-4FC4-AB1D-62109CF2687C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D64017C1-B9DD-4FC4-AB1D-62109CF2687C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D64017C1-B9DD-4FC4-AB1D-62109CF2687C}.Release|Any CPU.Build.0 = Release|Any CPU
{DCB64163-DF91-4EE8-ABE1-D90AE8DCA54B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DCB64163-DF91-4EE8-ABE1-D90AE8DCA54B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DCB64163-DF91-4EE8-ABE1-D90AE8DCA54B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DCB64163-DF91-4EE8-ABE1-D90AE8DCA54B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
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 port = configuration.GetValue<int>("port");
var enabled = configuration.GetValue<bool>("enabled");
var apiUrl = configuration.GetValue<Uri>("apiUrl");

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

// This will output the following:
// Port = 5001
// Enabled = True
// API URL = https://jsonplaceholder.typicode.com/
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<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="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.2" />
</ItemGroup>

</Project>
2 changes: 2 additions & 0 deletions docs/fundamentals/toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1014,6 +1014,8 @@ items:
- name: Configuration providers
href: ../core/extensions/configuration-providers.md
displayName: configuration providers,config providers
- name: Configuration source generation
href: ../core/extensions/configuration-generator.md
- name: Implement a custom configuration provider
href: ../core/extensions/custom-configuration-provider.md
displayName: custom configuration,custom config,custom configuration provider,custom config provider
Expand Down
Loading