/ src / modules / cmdpal / Microsoft.CmdPal.UI / TypePreservation.cs
TypePreservation.cs
 1  // Copyright (c) Microsoft Corporation
 2  // The Microsoft Corporation licenses this file to you under the MIT license.
 3  // See the LICENSE file in the project root for more information.
 4  
 5  using System.Diagnostics.CodeAnalysis;
 6  using Microsoft.UI.Xaml;
 7  using Microsoft.UI.Xaml.Controls;
 8  
 9  namespace Microsoft.CmdPal.UI;
10  
11  /// <summary>
12  /// This class ensures types used in XAML are preserved during AOT compilation.
13  /// Framework types cannot have attributes added directly to their definitions since they're external types.
14  /// Application types that require runtime type checking should also be preserved here if needed.
15  /// </summary>
16  internal static class TypePreservation
17  {
18      /// <summary>
19      /// This method ensures critical types are preserved for AOT compilation.
20      /// These types are used dynamically in XAML and would otherwise be trimmed.
21      /// </summary>
22      [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(Microsoft.UI.Xaml.Controls.FontIconSource))]
23      [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(Microsoft.UI.Xaml.Controls.PathIcon))]
24      [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(Microsoft.UI.Xaml.DataTemplate))]
25      [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(Microsoft.UI.Xaml.Controls.DataTemplateSelector))]
26      [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(Microsoft.UI.Xaml.Controls.ListViewItem))]
27      public static void PreserveTypes()
28      {
29          // This method exists only to hold the DynamicDependency attributes above.
30          // It must be called to ensure the types are not trimmed during AOT compilation.
31  
32          // Note: We cannot add [DynamicallyAccessedMembers] directly to framework types
33          // since we don't own their source code. DynamicDependency is the correct approach
34          // for preserving external types that are used dynamically (e.g., in XAML).
35  
36          // For application types that require runtime type checking (e.g., in template selectors),
37          // prefer adding [DynamicallyAccessedMembers] attributes directly on the type definitions.
38          // Only use DynamicDependency here for types we cannot modify directly.
39      }
40  }