Skip to content

[API Proposal]: trim-safe RuntimeHelpers.RunClassConstructor(Type) overload #103679

@Sergio0694

Description

@Sergio0694

Background and motivation

In the XAML compiler, when targeting modern .NET, we need to invoke RuntimeHelpers.RunClassConstructor to make sure that the static constructor for a given type is initialized before some other code runs. Most scenarios for this revolve around dependency properties, which in some cases need to be initialized and registered in the WinRT runtime before some other code runs (eg. before the activation factory for a given type is retrieved). To make this trim-safe, the lifted XAML compiler was updated with a bunch of [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] annotations on all such types, and a suppression on the method calling RuntimeHelpers.RunClassConstructor with these types.

You can see the use in the XAML compiler here.

However, talking with @agocke and @SingleAccretion today, they pointed out that this pattern is not supported, and it's not guaranteed to work. So this proposal is for a safe, annotated overload of the same method, taking a Type instance instead.

API Proposal

 namespace System.Diagnostics.CodeAnalysis
 {
     public enum DynamicallyAccessedMemberTypes
     {
+        StaticConstructor = 0x4000,
     }
 }

 namespace System.Runtime.CompilerServices
 {
     public static partial class RuntimeHelpers
     {
+        public static void RunClassConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.StaticConstructor)] Type type);
     }
 }

API Usage

[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.StaticConstructor)]
public Type UnderlyingType => _underlyingType;

private void RunInitializerImplementation()
{
    RuntimeHelpers.RunClassConstructor(UnderlyingType.TypeHandle);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-NativeAOT-coreclrlinkable-frameworkIssues associated with delivering a linker friendly framework

    Type

    No type

    Projects

    Status

    No status

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions