Skip to content

Commit

Permalink
Enable AOT compatibility for all libraries (#4871)
Browse files Browse the repository at this point in the history
* Enable AOT compatibility for all libraries (#4625)

* Enable AOT compatibility for all libraries. Fix warnings.

- Enable configuration binder source generator
- The only library that can't use the ConfigBinder SG is the HeaderParsing library.
  - Blocked by dotnet/runtime#94547

* Fix Compliance Redaction.

* Explicitly reference Microsoft.Extensions.Configuration.Binder

For all libraries that use the Configuration.Binder source generator, explicitly reference the NuGet package. This ensures we get the latest version (8.0.1), which has all the source generator fixes.

* Respond to PR feedback.

- Change ArgumentNullException to normal ArgumentException
- Add tests to LoggingRedactionOptions collection setters to keep 100% code coverage. dotnet/runtime#96873 causes these setters to no longer be called in the existing tests.
  • Loading branch information
eerhardt committed Jan 12, 2024
1 parent 7db3a7e commit d58517b
Show file tree
Hide file tree
Showing 41 changed files with 113 additions and 135 deletions.
6 changes: 0 additions & 6 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,6 @@
<MsbuildTaskMicrosoftCodeAnalysisCSharpVersion>$(MicrosoftCodeAnalysisCSharpVersion)</MsbuildTaskMicrosoftCodeAnalysisCSharpVersion>
</PropertyGroup>

<Target Name="DisableBrokenAnalyzers" BeforeTargets="CoreCompile">
<ItemGroup>
<Analyzer Remove="@(Analyzer)" Condition="'%(Filename)' == 'Microsoft.Extensions.Configuration.Binder.SourceGeneration'"/>
</ItemGroup>
</Target>

<!-- Test configuration -->
<PropertyGroup>
<!-- Disable building Integration Test projects in LUT. -->
Expand Down
1 change: 1 addition & 0 deletions src/Libraries/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<PropertyGroup>
<TargetFrameworks>$(NetCoreTargetFrameworks)$(ConditionalNet462)</TargetFrameworks>
<IsTrimmable Condition="'$(IsTrimmable)' == '' and $([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net6.0'))">true</IsTrimmable>
<IsAotCompatible Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net7.0'))">true</IsAotCompatible>

<InjectDiagnosticAttributesOnLegacy Condition="'$(InjectDiagnosticAttributesOnLegacy)' == ''">true</InjectDiagnosticAttributesOnLegacy>
<InjectIsExternalInitOnLegacy Condition="'$(InjectIsExternalInitOnLegacy)' == ''">true</InjectIsExternalInitOnLegacy>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Diagnostics.Latency;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
Expand Down Expand Up @@ -64,11 +63,6 @@ public static IServiceCollection AddRequestLatencyTelemetry(this IServiceCollect
/// <param name="section">Configuration of <see cref="RequestLatencyTelemetryOptions"/>.</param>
/// <returns>The value of <paramref name="services"/>.</returns>
/// <exception cref="ArgumentNullException">Either <paramref name="services"/> or <paramref name="section"/> is <see langword="null" />.</exception>
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicParameterlessConstructor, type: typeof(RequestLatencyTelemetryOptions))]
[UnconditionalSuppressMessage(
"Trimming",
"IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code",
Justification = "Addressed with [DynamicDependency]")]
public static IServiceCollection AddRequestLatencyTelemetry(this IServiceCollection services, IConfigurationSection section)
=> Throw.IfNull(services)
.Configure<RequestLatencyTelemetryOptions>(Throw.IfNull(section))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public static IServiceCollection AddHttpLoggingRedaction(this IServiceCollection
{
_ = Throw.IfNull(section);

return services.AddHttpLoggingRedaction(section.Bind);
return services.AddHttpLoggingRedaction(o => section.Bind(o));
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

<PropertyGroup>
<TargetFrameworks>$(NetCoreTargetFrameworks)</TargetFrameworks>
<EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
<UseLoggingGenerator>true</UseLoggingGenerator>
<InjectSharedThrow>false</InjectSharedThrow>
<InjectTrimAttributesOnLegacy>false</InjectTrimAttributesOnLegacy>
Expand Down Expand Up @@ -38,6 +39,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" />
<PackageReference Include="Microsoft.IO.RecyclableMemoryStream" />
<PackageReference Include="System.Collections.Immutable" Condition="!$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net8.0'))" />
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Condition="!$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net7.0'))" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

<PropertyGroup>
<TargetFrameworks>$(NetCoreTargetFrameworks)</TargetFrameworks>
<!-- blocked by https://github.com/dotnet/runtime/issues/94547 -->
<IsAotCompatible>false</IsAotCompatible>
<UseLoggingGenerator>true</UseLoggingGenerator>
<UseMetricsGenerator>true</UseMetricsGenerator>
<InjectExperimentalAttributeOnLegacy>true</InjectExperimentalAttributeOnLegacy>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.AmbientMetadata;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Shared.Diagnostics;
Expand All @@ -25,11 +23,6 @@ public static class ApplicationMetadataHostBuilderExtensions
/// <returns>The value of <paramref name="builder"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="builder"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="sectionName"/> is either <see langword="null"/>, empty, or whitespace.</exception>
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicParameterlessConstructor, typeof(ApplicationMetadata))]
[UnconditionalSuppressMessage(
"Trimming",
"IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code",
Justification = "Addressed with [DynamicDependency]")]
public static IHostBuilder UseApplicationMetadata(this IHostBuilder builder, string sectionName = DefaultSectionName)
{
_ = Throw.IfNull(builder);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.AmbientMetadata;
using Microsoft.Extensions.Configuration;
using Microsoft.Shared.Diagnostics;
Expand All @@ -21,11 +20,6 @@ public static class ApplicationMetadataServiceCollectionExtensions
/// <param name="section">The configuration section to bind.</param>
/// <returns>The value of <paramref name="services"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="section"/> or <paramref name="section"/> is <see langword="null"/>.</exception>
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicParameterlessConstructor, typeof(ApplicationMetadata))]
[UnconditionalSuppressMessage(
"Trimming",
"IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code",
Justification = "Addressed with [DynamicDependency]")]
public static IServiceCollection AddApplicationMetadata(this IServiceCollection services, IConfigurationSection section)
{
_ = Throw.IfNull(services);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
<Workstream>Fundamentals</Workstream>
</PropertyGroup>

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

<PropertyGroup>
<Stage>normal</Stage>
<MinCodeCoverage>100</MinCodeCoverage>
Expand All @@ -15,6 +19,7 @@
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" />
<PackageReference Include="Microsoft.Extensions.Configuration" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

<PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
<InjectStringSyntaxAttributeOnLegacy>true</InjectStringSyntaxAttributeOnLegacy>
<InjectExperimentalAttributeOnLegacy>true</InjectExperimentalAttributeOnLegacy>
<InjectSharedDiagnosticIds>true</InjectSharedDiagnosticIds>
Expand All @@ -25,6 +26,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" />
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Condition="!$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net7.0'))" />
<PackageReference Include="System.Collections.Immutable" Condition="!$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net8.0'))" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Compliance.Classification;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
Expand Down Expand Up @@ -45,11 +44,6 @@ public static IRedactionBuilder SetHmacRedactor(this IRedactionBuilder builder,
/// <param name="classifications">The data classifications for which the redactor type should be used.</param>
/// <returns>The value of <paramref name="builder" />.</returns>
/// <exception cref="ArgumentNullException"><paramref name="builder"/>, <paramref name="section" />, or <paramref name="classifications" /> is <see langword="null"/>.</exception>
[DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(HmacRedactorOptions))]
[UnconditionalSuppressMessage(
"Trimming",
"IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code",
Justification = "Addressed with [DynamicDependency]")]
public static IRedactionBuilder SetHmacRedactor(this IRedactionBuilder builder, IConfigurationSection section, params DataClassificationSet[] classifications)
{
_ = Throw.IfNull(builder);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Compliance.Classification;
using Microsoft.Extensions.Compliance.Redaction;
using Microsoft.Extensions.Compliance.Testing;
Expand Down Expand Up @@ -65,9 +64,6 @@ public static IRedactionBuilder SetFakeRedactor(this IRedactionBuilder builder,
/// <param name="classifications">The data classifications for which the redactor type should be used.</param>
/// <returns>The value of <paramref name="builder" />.</returns>
/// <exception cref="ArgumentNullException"><paramref name="builder"/> or <paramref name="section"/> is <see langword="null"/>.</exception>
[UnconditionalSuppressMessage("Trimming",
"IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code",
Justification = "The type is FakeRedactorOptions and we know it.")]
public static IRedactionBuilder SetFakeRedactor(this IRedactionBuilder builder, IConfigurationSection section, params DataClassificationSet[] classifications)
{
_ = Throw.IfNull(builder);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
</PropertyGroup>

<PropertyGroup>
<EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
<UseLoggingGenerator>true</UseLoggingGenerator>
<InjectExperimentalAttributeOnLegacy>true</InjectExperimentalAttributeOnLegacy>
<InjectStringSyntaxAttributeOnLegacy>true</InjectStringSyntaxAttributeOnLegacy>
Expand All @@ -24,6 +25,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" />
<PackageReference Include="Microsoft.Bcl.HashCode" Condition="!$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net6.0'))" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,9 @@ public static partial class AutoActivationExtensions
/// <param name="serviceType">The type of the service to activate.</param>
/// <param name="serviceKey">An object used to uniquely identify the specific service.</param>
/// <returns>The value of <paramref name="services" />.</returns>
[UnconditionalSuppressMessage(
"Trimming",
"IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code",
Justification = "Addressed with [DynamicallyAccessedMembers]")]
public static IServiceCollection ActivateKeyedSingleton(
this IServiceCollection services,
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType,
Type serviceType,
object? serviceKey)
{
_ = Throw.IfNull(services);
Expand All @@ -72,7 +68,7 @@ public static partial class AutoActivationExtensions
.AddOptions<AutoActivatorOptions>()
.Configure(ao =>
{
var constructed = typeof(IEnumerable<>).MakeGenericType(serviceType);
var constructed = GetEnumerableServiceType(serviceType);
if (ao.KeyedAutoActivators.Contains((constructed, serviceKey)))
{
return;
Expand All @@ -85,6 +81,10 @@ public static partial class AutoActivationExtensions
}
_ = ao.KeyedAutoActivators.Add((serviceType, serviceKey));
[UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode",
Justification = "When IsDynamicCodeSupported is not supported, DependencyInjection ensures IEnumerable service types are not a ValueType.")]
static Type GetEnumerableServiceType(Type serviceType) => typeof(IEnumerable<>).MakeGenericType(serviceType);
});

return services;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,7 @@ public static IServiceCollection ActivateSingleton<TService>(this IServiceCollec
/// <param name="services">The service collection containing the service.</param>
/// <param name="serviceType">The type of the service to activate.</param>
/// <returns>The value of <paramref name="services" />.</returns>
[UnconditionalSuppressMessage(
"Trimming",
"IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code",
Justification = "Addressed with [DynamicallyAccessedMembers]")]
public static IServiceCollection ActivateSingleton(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType)
public static IServiceCollection ActivateSingleton(this IServiceCollection services, Type serviceType)
{
_ = Throw.IfNull(services);
_ = Throw.IfNull(serviceType);
Expand All @@ -69,7 +65,7 @@ public static IServiceCollection ActivateSingleton(this IServiceCollection servi
.AddOptions<AutoActivatorOptions>()
.Configure(ao =>
{
var constructed = typeof(IEnumerable<>).MakeGenericType(serviceType);
var constructed = GetEnumerableServiceType(serviceType);
if (ao.AutoActivators.Contains(constructed))
{
return;
Expand All @@ -82,6 +78,10 @@ public static IServiceCollection ActivateSingleton(this IServiceCollection servi
}
_ = ao.AutoActivators.Add(serviceType);
[UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode",
Justification = "When IsDynamicCodeSupported is not supported, DependencyInjection ensures IEnumerable service types are not a ValueType.")]
static Type GetEnumerableServiceType(Type serviceType) => typeof(IEnumerable<>).MakeGenericType(serviceType);
});

return services;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,19 +35,29 @@ static HttpExceptionSummaryProvider()
};

var socketErrors = new Dictionary<SocketError, int>();
#if NET5_0_OR_GREATER
foreach (var socketError in Enum.GetValues<SocketError>())
{
#else
foreach (var v in Enum.GetValues(typeof(SocketError)))
{
var socketError = (SocketError)v!;
#endif
var name = socketError.ToString();

socketErrors[socketError] = descriptions.Count;
descriptions.Add(name);
}

var webStatuses = new Dictionary<WebExceptionStatus, int>();
#if NET5_0_OR_GREATER
foreach (var status in Enum.GetValues<WebExceptionStatus>())
{
#else
foreach (var v in Enum.GetValues(typeof(WebExceptionStatus)))
{
var status = (WebExceptionStatus)v!;
#endif
var name = status.ToString();

webStatuses[status] = descriptions.Count;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<RootNamespace>Microsoft.Extensions.Diagnostics.HealthChecks</RootNamespace>
<Description>Health check implementations.</Description>
<Workstream>Resilience</Workstream>
</PropertyGroup>

<PropertyGroup>
<EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
<UseLoggingGenerator>true</UseLoggingGenerator>
<UseMetricsGenerator>true</UseMetricsGenerator>
<InjectSharedPools>true</InjectSharedPools>
Expand All @@ -22,6 +23,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" />
<PackageReference Include="Microsoft.Extensions.Diagnostics" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" />
<XPackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
</PropertyGroup>

<PropertyGroup>
<EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
<InjectSharedDataValidation>true</InjectSharedDataValidation>
<InjectExperimentalAttributeOnLegacy>true</InjectExperimentalAttributeOnLegacy>
</PropertyGroup>
Expand All @@ -21,6 +22,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" />
</ItemGroup>

Expand Down
Loading

0 comments on commit d58517b

Please sign in to comment.