Skip to content

chore: preserve properties on generated ViewModels - #2969

Merged
jonpryor merged 1 commit into
mainfrom
dev/jonpryor/jonp-preserve-generated-bindable-props
Dec 4, 2025
Merged

jonpryor merged 1 commit into
mainfrom
dev/jonpryor/jonp-preserve-generated-bindable-props

Conversation

@jonpryor

@jonpryor jonpryor commented Dec 2, 2025

Copy link
Copy Markdown
Contributor

Context: #2966
Context: unoplatform/uno.chefs#1709

While running the uno.chefs app on macOS under NativeAOT:

dotnet publish -c Release -r osx-x64 -f net10.0-desktop -p:TargetFrameworkOverride=net10.0-desktop -bl \
  Chefs/Chefs.csproj \
  -p:SelfContained=true -p:PublishAot=true -p:IsAotCompatible=true -p:UseSkiaRendering=true \
  -p:IlcGenerateMapFile=true -p:IlcGenerateMstatFile=true -p:IlcGenerateDgmlFile=true \
  -p:EmitCompilerGeneratedFiles=true -p:CompilerGeneratedFilesOutputPath=`pwd`/_gen
Chefs/bin/Release/net10.0-desktop/osx-x64/publish/Chefs

(along with a change from unoplatform/uno.chefs#1709 to Program.cs to call App.InitializeLogging()…)

Console output would contain the following error:

fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
      The [CurrentIndex] property getter does not exist on type [Chefs.Business.Models.BindableIntIteratorViewModel]
fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
      The property setter for [CurrentIndex] does not exist on [Chefs.Business.Models.BindableIntIteratorViewModel]
fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
      The [Value] property getter does not exist on type [Chefs.Business.Models.BindableIntIteratorViewModel]

PR #2966 had a similar set of messages, and the general fix is to use [DynamicallyAccessedMembers] so that NativeAOT preserves property metadata.

The problem here is that there is no good place to put [DynamicallyAccessedMembers] that will preserve the ViewModel types generated by Uno.Extensions.Reactive.Generator:

namespace Chefs.Business.Models {
  [GeneratedCodeAttribute("ViewModelGenerator_2", "2")]
  [Bindable(typeof(IntIterator))]
  public partial class BindableIntIteratorViewModel : global::Uno.Extensions.Reactive.Bindings.Bindable<Chefs.Business.Models.IntIterator> {
    public IntIterator Value {get => …; set => …;}
    public int CurrentIndex {get => …; set => …;}
  }
}
namespace Chefs.Presentation {
  [GeneratedCodeAttribute("ViewModelGenTool_3", "3")]
  [Bindable(typeof(global::Chefs.Presentation.WelcomeModel))]
  public partial class WelcomeViewModel {
    protected WelcomeViewModel(global::Chefs.Presentation.WelcomeModel model) {
      // …
      Pages ??= new Chefs.Business.Models.BindableIntIteratorViewModel(…);
      // …
    }
    public Chefs.Business.Models.BindableIntIteratorViewModel Pages { get; private set; }
  }
}

Nothing tells NativeAOT to preserve the BindableIntIteratorViewModel properties, so they're "removed" from Reflection metadata.

Update BindableFromFeedProperty.cs to use [DynamicDependency] on the WelcomeViewModel.Pages property accessor:

namespace Chefs.Presentation {
  public partial class WelcomeViewModel {
    public Chefs.Business.Models.BindableIntIteratorViewModel Pages
    {
      [DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(Chefs.Business.Models.BindableIntIteratorViewModel))]
      get;
      private set;
    }
  }
}

This change informs NativeAOT that if the WelcomeViewModel.Pages property getter is preserved, then the public properties on BindableIntIteratorViewModel should also be made accessible via Reflection. This fixes the original message:

fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
      The [CurrentIndex] property getter does not exist on type [Chefs.Business.Models.BindableIntIteratorViewModel]

…only to replace it with this different set of failure messages:

fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
      The [CanMovePrevious] property getter does not exist on type [Chefs.Business.Models.IntIterator]
fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
      The [CanMovePrevious] property getter does not exist on type [Chefs.Business.Models.IntIterator]
fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
      The [CanMoveNext] property getter does not exist on type [Chefs.Business.Models.IntIterator]
fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
      The [CanMoveNext] property getter does not exist on type [Chefs.Business.Models.IntIterator]

Address this new set of messages by updating Bindable<T> to

partial class Bindable<
  [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicProperties)]
  T
> : IBindable
{
}

As BindableIntIteratorViewModel inherits from Bindable<IntIterator> this causes the public properties on IntIterator to be preserved, fixing the previous set of failure messages.

GitHub Issue (If applicable): closes #

PR Type

What kind of change does this PR introduce?

What is the current behavior?

What is the new behavior?

PR Checklist

Please check if your PR fulfills the following requirements:

  • Tested code with current supported SDKs
  • Docs have been added/updated which fit documentation template. (for bug fixes / features)
  • Unit Tests and/or UI Tests for the changes have been added (for bug fixes / features) (if applicable)
  • Wasm UI Tests are not showing unexpected any differences. Validate PR Screenshots Compare Test Run results.
  • Contains NO breaking changes
  • Updated the Release Notes
  • Associated with an issue (GitHub or internal)

Other information

Internal Issue (If applicable):

jonpryor added a commit to unoplatform/uno that referenced this pull request Dec 2, 2025
Context: unoplatform/uno.chefs#1712
Context: #21920
Context: unoplatform/uno.extensions#2966
Context: unoplatform/uno.extensions#2969
Context: https://discord.com/channels/732297728826277939/732297837953679412/1444909702512119899

While running the uno.chefs app on macOS under NativeAOT:

	dotnet publish -c Release -r osx-x64 -f net10.0-desktop -p:TargetFrameworkOverride=net10.0-desktop -bl \
	  Chefs/Chefs.csproj \
	  -p:SelfContained=true -p:PublishAot=true -p:IsAotCompatible=true -p:UseSkiaRendering=true \
	  -p:IlcGenerateMapFile=true -p:IlcGenerateMstatFile=true -p:IlcGenerateDgmlFile=true \
	  -p:EmitCompilerGeneratedFiles=true -p:CompilerGeneratedFilesOutputPath=`pwd`/_gen
	Chefs/bin/Release/net10.0-desktop/osx-x64/publish/Chefs

(along with a change from unoplatform/uno.chefs#1712)

Console output would contain the following errors:

	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView]
	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [Y] property getter does not exist on type [Windows.Foundation.Point]
	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [X] property getter does not exist on type [Windows.Foundation.Point]

At this point, a description of the relation between NativeAOT and
Reflection would be useful.

Parts of System.Reflection can be used.  Which parts *can* be used,
and how to use them, is oddly *not* well specified in the
[Native AOT deployment][0] documentation.

What doesn't work is outlined in the [limitations][1] section:

> * No dynamic loading, for example, `Assembly.LoadFile`.
> * No run-time code generation, for example, `System.Reflection.Emit`.

What *always* appears to work is:

  * `Type.GetType()` returns a `Type` instance.

What ***can*** work is:

  * `Type.GetType(string)`, *so long as* an assembly-qualified name
    is used as a *string constant*

        // bad
        string name = GetSomeTypeName();
        Type type = Type.GetType(name);

        // good
        Type type = Type.GetType("My.Example.TypeName, ExampleAssembly");

  * `Type.GetMethods()`, but see fine print below.
  * `Type.GetProperties()`, but see fine print below.
  * `MethodInfo.Invoke()`
  * …

**The Fine Print**: in order for many Reflection-based APIs such as
`Type.GetMethods()` to work, the program must contain
"reflection metadata."

We can now describe, briefly, what NativeAOT does:

 1. Accept IL/assemblies
 2. Internally trims the IL, optimizes them, etc.
 3. Generates a native binary containing two separate bits of data:

    * Native machine code for execution
    * "reflection metadata"

There is no facility to separately dump reflection metadata.

Programs can control what is contained within reflection metadata
by using string constants with Reflection APIs, for example:

	typeof(SomeKnownType).GetMethod("ConstantName")

will ensure that reflection metadata contains
`SomeKnownType.ConstantName()`, and `ConstantName()` will be returned
from `typeof(SomeKnownType).GetMethods()` and can be invoked with
`MethodInfo.Invoke()`.

If you *don't* use `typeof(SomeKnownType)` or string constants with
`Type.GetType(string)` or `type.GetMethod("constant")`, then you need
to "suggest" that some pieces of information be added to
reflection metadata.

The two predominant ways to do this are via the custom attributes:

  * [`DynamicallyAccessedMembersAttribute`][2]
  * [`DynamicDependencyAttribute`][3]

From the Uno perspective, enter `BindingPropertyHelper`: *everything*
is based on Reflection!

Fortunately NativeAOT "supports" Reflection!

*Unfortunately*, we now need to convince NativeAOT to store the
reflection metadata Uno requires in order to work!

Various other PRs have dealt with some of this, such as #21920.

Returning to the original failure messages, e.g.

	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView]

During the app build, `src/SourceGenerators/Uno.UI.SourceGenerators`
generates a a `BindableMetadata.g.cs` file which will mention
`[Bindable]` types, e.g. for `Microsoft.UI.Xaml.Controls.FlipView`:

	/// <summary>
	/// Builder for Microsoft.UI.Xaml.Controls.FlipView
	/// </summary>
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	static class MetadataBuilder_239
	{
	  internal static global::Uno.UI.DataBinding.IBindableType Build(global::Uno.UI.DataBinding.BindableType parent)
	  {
	    var bindableType = parent ?? new global::Uno.UI.DataBinding.BindableType(151, typeof(global::Microsoft.UI.Xaml.Controls.FlipView));
	    // …
	  }
	  private static object CreateInstance() => new global::Microsoft.UI.Xaml.Controls.FlipView();
	}

`BindableMetadata.g.cs` was needed in the ye olde Xamarin world order
to tell *its* linker to e.g. "preserve the `FlipView` default ctor!"

*Now*, we can build upon this infrastructure and update `BindableType`
to request that Reflection information regarding properties, fields,
and constructors be retained.  We can do this by updating the
`BindableType` constructor:

	partial class BindableType {
	  internal const DynamicallyAccessedMemberTypes TypeRequirements =
	    DynamicallyAccessedMemberTypes.PublicProperties | …;
	  public BindableType(int estimatedPropertySize, [DynamicallyAccessedMembers(TypeRequirements)] Type sourceType ) => …
	}

*Because* we have `BindableMetadata.g.cs` *and* because it provides
`typeof(FlipView)`, this directs NativeAOT to make property and other
reflection metadata available to the app, *fixing* the error messages.

Expand this addition of `[DynamicallyAccessedMembers]` to also include
`BindableProperty` and related types.

[0]: https://learn.microsoft.comdotnet/core/deploying/native-aot
[1]: https://learn.microsoft.comdotnet/core/deploying/native-aot/#limitations-of-native-aot-deployment
[2]: https://learn.microsoft.comdotnet/api/system.diagnostics.codeanalysis.dynamicallyaccessedmembersattribute?view=net-10.0
[3]: https://learn.microsoft.comdotnet/api/system.diagnostics.codeanalysis.dynamicdependencyattribute?view=net-10.0
Context: #2966

While running the uno.chefs app on macOS under NativeAOT:

	dotnet publish -c Release -r osx-x64 -f net10.0-desktop -p:TargetFrameworkOverride=net10.0-desktop -bl \
	  Chefs/Chefs.csproj \
	  -p:SelfContained=true -p:PublishAot=true -p:IsAotCompatible=true -p:UseSkiaRendering=true \
	  -p:IlcGenerateMapFile=true -p:IlcGenerateMstatFile=true -p:IlcGenerateDgmlFile=true \
	  -p:EmitCompilerGeneratedFiles=true -p:CompilerGeneratedFilesOutputPath=`pwd`/_gen
	Chefs/bin/Release/net10.0-desktop/osx-x64/publish/Chefs

Console output would contain the following error:

	fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
	      The [CurrentIndex] property getter does not exist on type [Chefs.Business.Models.BindableIntIteratorViewModel]
	fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
	      The property setter for [CurrentIndex] does not exist on [Chefs.Business.Models.BindableIntIteratorViewModel]
	fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
	      The [Value] property getter does not exist on type [Chefs.Business.Models.BindableIntIteratorViewModel]

PR #2966 had a similar set of messages, and the general fix is to use
`[DynamicallyAccessedMembers]` so that NativeAOT preserves property
metadata.

The problem *here* is that there is no good place to put
`[DynamicallyAccessedMembers]` that will preserve the ViewModel types
generated by Uno.Extensions.Reactive.Generator:

	namespace Chefs.Business.Models {
	  [GeneratedCodeAttribute("ViewModelGenerator_2", "2")]
	  [Bindable(typeof(IntIterator))]
	  public partial class BindableIntIteratorViewModel : global::Uno.Extensions.Reactive.Bindings.Bindable<Chefs.Business.Models.IntIterator> {
	    public IntIterator Value {get => …; set => …;}
	    public int CurrentIndex {get => …; set => …;}
	  }
	}
	namespace Chefs.Presentation {
	  [GeneratedCodeAttribute("ViewModelGenTool_3", "3")]
	  [Bindable(typeof(global::Chefs.Presentation.WelcomeModel))]
	  public partial class WelcomeViewModel {
	    protected WelcomeViewModel(global::Chefs.Presentation.WelcomeModel model) {
	      // …
	      Pages ??= new Chefs.Business.Models.BindableIntIteratorViewModel(…);
	      // …
	    }
	    public Chefs.Business.Models.BindableIntIteratorViewModel Pages { get; private set; }
	  }
	}

Nothing tells NativeAOT to preserve the `BindableIntIteratorViewModel`
properties, so they're "removed" from Reflection metadata.

Update `BindableFromFeedProperty.cs` to use `[DynamicDependency]`
on the `WelcomeViewModel.Pages` property accessor:

	namespace Chefs.Presentation {
	  public partial class WelcomeViewModel {
	    public Chefs.Business.Models.BindableIntIteratorViewModel Pages
	    {
	      [DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(Chefs.Business.Models.BindableIntIteratorViewModel))]
	      get;
	      private set;
	    }
	  }
	}

This change informs NativeAOT that if the `WelcomeViewModel.Pages`
property getter is preserved, then the public properties on
`BindableIntIteratorViewModel` should also be made accessible via
Reflection.  This fixes the original message:

	fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
	      The [CurrentIndex] property getter does not exist on type [Chefs.Business.Models.BindableIntIteratorViewModel]

…only to replace it with this *different* set of failure messages:

	fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
	      The [CanMovePrevious] property getter does not exist on type [Chefs.Business.Models.IntIterator]
	fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
	      The [CanMovePrevious] property getter does not exist on type [Chefs.Business.Models.IntIterator]
	fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
	      The [CanMoveNext] property getter does not exist on type [Chefs.Business.Models.IntIterator]
	fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
	      The [CanMoveNext] property getter does not exist on type [Chefs.Business.Models.IntIterator]

Address this new set of messages by updating `Bindable<T>` to

	partial class Bindable<
	  [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)]
	  T
	> : IBindable
	{
	}

As `BindableIntIteratorViewModel` inherits from `Bindable<IntIterator>`
this causes the public properties on `IntIterator` to be preserved,
fixing the previous set of failure messages.

Adding `[DynamicallyAccessedMembers]` to `Bindable<T>` breaks
`BindableEnumerable<…>`:

	BindableEnumerable.cs(22,23): error IL2091:
	  'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicProperties' in 'Uno.Extensions.Reactive.Bindings.Bindable<T>'.
	  The generic parameter 'TCollection' of 'Uno.Extensions.Reactive.Bindings.BindableEnumerable<TCollection, TItem, TBindableItem>' does not have matching annotations.
	  The source value must declare at least the same requirements as those declared on the target location it is assigned to.

Annotate the `TCollection` type parameter accordingly to fix the error.
@jonpryor
jonpryor force-pushed the dev/jonpryor/jonp-preserve-generated-bindable-props branch from 21ccf69 to 8870ddf Compare December 3, 2025 12:55
jonpryor added a commit to unoplatform/uno that referenced this pull request Dec 3, 2025
Context: unoplatform/uno.chefs#1712
Context: #21920
Context: unoplatform/uno.extensions#2966
Context: unoplatform/uno.extensions#2969
Context: https://discord.com/channels/732297728826277939/732297837953679412/1444909702512119899

While running the uno.chefs app on macOS under NativeAOT:

	dotnet publish -c Release -r osx-x64 -f net10.0-desktop -p:TargetFrameworkOverride=net10.0-desktop -bl \
	  Chefs/Chefs.csproj \
	  -p:SelfContained=true -p:PublishAot=true -p:IsAotCompatible=true -p:UseSkiaRendering=true \
	  -p:IlcGenerateMapFile=true -p:IlcGenerateMstatFile=true -p:IlcGenerateDgmlFile=true \
	  -p:EmitCompilerGeneratedFiles=true -p:CompilerGeneratedFilesOutputPath=`pwd`/_gen
	Chefs/bin/Release/net10.0-desktop/osx-x64/publish/Chefs

(along with a change from unoplatform/uno.chefs#1712)

Console output would contain the following errors:

	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView]
	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [Y] property getter does not exist on type [Windows.Foundation.Point]
	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [X] property getter does not exist on type [Windows.Foundation.Point]

At this point, a description of the relation between NativeAOT and
Reflection would be useful.

Parts of System.Reflection can be used.  Which parts *can* be used,
and how to use them, is oddly *not* well specified in the
[Native AOT deployment][0] documentation.

What doesn't work is outlined in the [limitations][1] section:

> * No dynamic loading, for example, `Assembly.LoadFile`.
> * No run-time code generation, for example, `System.Reflection.Emit`.

What *always* appears to work is:

  * `Type.GetType()` returns a `Type` instance.

What ***can*** work is:

  * `Type.GetType(string)`, *so long as* an assembly-qualified name
    is used as a *string constant*

        // bad
        string name = GetSomeTypeName();
        Type type = Type.GetType(name);

        // good
        Type type = Type.GetType("My.Example.TypeName, ExampleAssembly");

  * `Type.GetMethods()`, but see fine print below.
  * `Type.GetProperties()`, but see fine print below.
  * `MethodInfo.Invoke()`
  * …

**The Fine Print**: in order for many Reflection-based APIs such as
`Type.GetMethods()` to work, the program must contain
"reflection metadata."

We can now describe, briefly, what NativeAOT does:

 1. Accept IL/assemblies
 2. Internally trims the IL, optimizes them, etc.
 3. Generates a native binary containing two separate bits of data:

    * Native machine code for execution
    * "reflection metadata"

There is no facility to separately dump reflection metadata.

Programs can control what is contained within reflection metadata
by using string constants with Reflection APIs, for example:

	typeof(SomeKnownType).GetMethod("ConstantName")

will ensure that reflection metadata contains
`SomeKnownType.ConstantName()`, and `ConstantName()` will be returned
from `typeof(SomeKnownType).GetMethods()` and can be invoked with
`MethodInfo.Invoke()`.

If you *don't* use `typeof(SomeKnownType)` or string constants with
`Type.GetType(string)` or `type.GetMethod("constant")`, then you need
to "suggest" that some pieces of information be added to
reflection metadata.

The two predominant ways to do this are via the custom attributes:

  * [`DynamicallyAccessedMembersAttribute`][2]
  * [`DynamicDependencyAttribute`][3]

From the Uno perspective, enter `BindingPropertyHelper`: *everything*
is based on Reflection!

Fortunately NativeAOT "supports" Reflection!

*Unfortunately*, we now need to convince NativeAOT to store the
reflection metadata Uno requires in order to work!

Various other PRs have dealt with some of this, such as #21920.

Returning to the original failure messages, e.g.

	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView]

During the app build, `src/SourceGenerators/Uno.UI.SourceGenerators`
generates a a `BindableMetadata.g.cs` file which will mention
`[Bindable]` types, e.g. for `Microsoft.UI.Xaml.Controls.FlipView`:

	/// <summary>
	/// Builder for Microsoft.UI.Xaml.Controls.FlipView
	/// </summary>
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	static class MetadataBuilder_239
	{
	  internal static global::Uno.UI.DataBinding.IBindableType Build(global::Uno.UI.DataBinding.BindableType parent)
	  {
	    var bindableType = parent ?? new global::Uno.UI.DataBinding.BindableType(151, typeof(global::Microsoft.UI.Xaml.Controls.FlipView));
	    // …
	  }
	  private static object CreateInstance() => new global::Microsoft.UI.Xaml.Controls.FlipView();
	}

`BindableMetadata.g.cs` was needed in the ye olde Xamarin world order
to tell *its* linker to e.g. "preserve the `FlipView` default ctor!"

*Now*, we can build upon this infrastructure and update `BindableType`
to request that Reflection information regarding properties, fields,
and constructors be retained.  We can do this by updating the
`BindableType` constructor:

	partial class BindableType {
	  internal const DynamicallyAccessedMemberTypes TypeRequirements =
	    DynamicallyAccessedMemberTypes.PublicProperties | …;
	  public BindableType(int estimatedPropertySize, [DynamicallyAccessedMembers(TypeRequirements)] Type sourceType ) => …
	}

*Because* we have `BindableMetadata.g.cs` *and* because it provides
`typeof(FlipView)`, this directs NativeAOT to make property and other
reflection metadata available to the app, *fixing* the error messages.

Expand this addition of `[DynamicallyAccessedMembers]` to also include
`BindableProperty` and related types.

[0]: https://learn.microsoft.comdotnet/core/deploying/native-aot
[1]: https://learn.microsoft.comdotnet/core/deploying/native-aot/#limitations-of-native-aot-deployment
[2]: https://learn.microsoft.comdotnet/api/system.diagnostics.codeanalysis.dynamicallyaccessedmembersattribute?view=net-10.0
[3]: https://learn.microsoft.comdotnet/api/system.diagnostics.codeanalysis.dynamicdependencyattribute?view=net-10.0
jonpryor added a commit to unoplatform/uno that referenced this pull request Dec 3, 2025
Context: unoplatform/uno.chefs#1712
Context: #21920
Context: unoplatform/uno.extensions#2966
Context: unoplatform/uno.extensions#2969
Context: https://discord.com/channels/732297728826277939/732297837953679412/1444909702512119899

While running the uno.chefs app on macOS under NativeAOT:

	dotnet publish -c Release -r osx-x64 -f net10.0-desktop -p:TargetFrameworkOverride=net10.0-desktop -bl \
	  Chefs/Chefs.csproj \
	  -p:SelfContained=true -p:PublishAot=true -p:IsAotCompatible=true -p:UseSkiaRendering=true \
	  -p:IlcGenerateMapFile=true -p:IlcGenerateMstatFile=true -p:IlcGenerateDgmlFile=true \
	  -p:EmitCompilerGeneratedFiles=true -p:CompilerGeneratedFilesOutputPath=`pwd`/_gen
	Chefs/bin/Release/net10.0-desktop/osx-x64/publish/Chefs

(along with a change from unoplatform/uno.chefs#1712)

Console output would contain the following errors:

	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView]
	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [Y] property getter does not exist on type [Windows.Foundation.Point]
	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [X] property getter does not exist on type [Windows.Foundation.Point]

At this point, a description of the relation between NativeAOT and
Reflection would be useful.

Parts of System.Reflection can be used.  Which parts *can* be used,
and how to use them, is oddly *not* well specified in the
[Native AOT deployment][0] documentation.

What doesn't work is outlined in the [limitations][1] section:

> * No dynamic loading, for example, `Assembly.LoadFile`.
> * No run-time code generation, for example, `System.Reflection.Emit`.

What *always* appears to work is:

  * `Type.GetType()` returns a `Type` instance.

What ***can*** work is:

  * `Type.GetType(string)`, *so long as* an assembly-qualified name
    is used as a *string constant*

        // bad
        string name = GetSomeTypeName();
        Type type = Type.GetType(name);

        // good
        Type type = Type.GetType("My.Example.TypeName, ExampleAssembly");

  * `Type.GetMethods()`, but see fine print below.
  * `Type.GetProperties()`, but see fine print below.
  * `MethodInfo.Invoke()`
  * …

**The Fine Print**: in order for many Reflection-based APIs such as
`Type.GetMethods()` to work, the program must contain
"reflection metadata."

We can now describe, briefly, what NativeAOT does:

 1. Accept IL/assemblies
 2. Internally trims the IL, optimizes them, etc.
 3. Generates a native binary containing two separate bits of data:

    * Native machine code for execution
    * "reflection metadata"

There is no facility to separately dump reflection metadata.

Programs can control what is contained within reflection metadata
by using string constants with Reflection APIs, for example:

	typeof(SomeKnownType).GetMethod("ConstantName")

will ensure that reflection metadata contains
`SomeKnownType.ConstantName()`, and `ConstantName()` will be returned
from `typeof(SomeKnownType).GetMethods()` and can be invoked with
`MethodInfo.Invoke()`.

If you *don't* use `typeof(SomeKnownType)` or string constants with
`Type.GetType(string)` or `type.GetMethod("constant")`, then you need
to "suggest" that some pieces of information be added to
reflection metadata.

The two predominant ways to do this are via the custom attributes:

  * [`DynamicallyAccessedMembersAttribute`][2]
  * [`DynamicDependencyAttribute`][3]

From the Uno perspective, enter `BindingPropertyHelper`: *everything*
is based on Reflection!

Fortunately NativeAOT "supports" Reflection!

*Unfortunately*, we now need to convince NativeAOT to store the
reflection metadata Uno requires in order to work!

Various other PRs have dealt with some of this, such as #21920.

Returning to the original failure messages, e.g.

	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView]

During the app build, `src/SourceGenerators/Uno.UI.SourceGenerators`
generates a a `BindableMetadata.g.cs` file which will mention
`[Bindable]` types, e.g. for `Microsoft.UI.Xaml.Controls.FlipView`:

	/// <summary>
	/// Builder for Microsoft.UI.Xaml.Controls.FlipView
	/// </summary>
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	static class MetadataBuilder_239
	{
	  internal static global::Uno.UI.DataBinding.IBindableType Build(global::Uno.UI.DataBinding.BindableType parent)
	  {
	    var bindableType = parent ?? new global::Uno.UI.DataBinding.BindableType(151, typeof(global::Microsoft.UI.Xaml.Controls.FlipView));
	    // …
	  }
	  private static object CreateInstance() => new global::Microsoft.UI.Xaml.Controls.FlipView();
	}

`BindableMetadata.g.cs` was needed in the ye olde Xamarin world order
to tell *its* linker to e.g. "preserve the `FlipView` default ctor!"

*Now*, we can build upon this infrastructure and update `BindableType`
to request that Reflection information regarding properties, fields,
and constructors be retained.  We can do this by updating the
`BindableType` constructor:

	partial class BindableType {
	  internal const DynamicallyAccessedMemberTypes TypeRequirements =
	    DynamicallyAccessedMemberTypes.PublicProperties | …;
	  public BindableType(int estimatedPropertySize, [DynamicallyAccessedMembers(TypeRequirements)] Type sourceType ) => …
	}

*Because* we have `BindableMetadata.g.cs` *and* because it provides
`typeof(FlipView)`, this directs NativeAOT to make property and other
reflection metadata available to the app, *fixing* the error messages.

Expand this addition of `[DynamicallyAccessedMembers]` to also include
`BindableProperty` and related types.

[0]: https://learn.microsoft.comdotnet/core/deploying/native-aot
[1]: https://learn.microsoft.comdotnet/core/deploying/native-aot/#limitations-of-native-aot-deployment
[2]: https://learn.microsoft.comdotnet/api/system.diagnostics.codeanalysis.dynamicallyaccessedmembersattribute?view=net-10.0
[3]: https://learn.microsoft.comdotnet/api/system.diagnostics.codeanalysis.dynamicdependencyattribute?view=net-10.0
jonpryor added a commit to unoplatform/uno that referenced this pull request Dec 3, 2025
Context: unoplatform/uno.chefs#1712
Context: #21920
Context: unoplatform/uno.extensions#2966
Context: unoplatform/uno.extensions#2969
Context: https://discord.com/channels/732297728826277939/732297837953679412/1444909702512119899

While running the uno.chefs app on macOS under NativeAOT:

	dotnet publish -c Release -r osx-x64 -f net10.0-desktop -p:TargetFrameworkOverride=net10.0-desktop -bl \
	  Chefs/Chefs.csproj \
	  -p:SelfContained=true -p:PublishAot=true -p:IsAotCompatible=true -p:UseSkiaRendering=true \
	  -p:IlcGenerateMapFile=true -p:IlcGenerateMstatFile=true -p:IlcGenerateDgmlFile=true \
	  -p:EmitCompilerGeneratedFiles=true -p:CompilerGeneratedFilesOutputPath=`pwd`/_gen
	Chefs/bin/Release/net10.0-desktop/osx-x64/publish/Chefs

Console output would contain the following errors:

	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView]
	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [Y] property getter does not exist on type [Windows.Foundation.Point]
	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [X] property getter does not exist on type [Windows.Foundation.Point]

At this point, a description of the relation between NativeAOT and
Reflection would be useful.

*Parts* of System.Reflection can be used.  Which parts *can* be used,
and how to use them, is oddly *not* well specified in the
[Native AOT deployment][0] documentation.

What doesn't work is outlined in the [limitations][1] section:

> * No dynamic loading, for example, `Assembly.LoadFile`.
> * No run-time code generation, for example, `System.Reflection.Emit`.

What *always* appears to work is:

  * `Type.GetType()` returns a `Type` instance.

What ***can*** work is:

  * `Type.GetType(string)`, *so long as* an assembly-qualified name
    is used as a *string constant*

        // bad
        string name = GetSomeTypeName();
        Type type = Type.GetType(name);

        // good
        Type type = Type.GetType("My.Example.TypeName, ExampleAssembly");

  * `Type.GetMethod(string)`, but see fine print below.
  * `Type.GetProperty(string)`, but see fine print below.
  * `MethodInfo.Invoke()`
  * …

**The Fine Print**: in order for many Reflection-based APIs such as
`Type.GetMethod(string)` to work, the program must contain
"reflection metadata."

We can now describe, briefly, what NativeAOT does:

 1. Accept IL/assemblies as input
 2. Internally trim the IL, optimizes them, etc.
 3. Generates a native binary containing two separate bits of data:

    * Native machine code for execution
    * "reflection metadata"

You can get an inkling of what methods survived trimming and become
native code by using `dotnet publish -p:IlcGenerateMapFile=true …`,
which will produce a `.mstat` file, a PE file which references every
type and member which is in the native binary, ***after*** inlining.
(Meaning if a member is inlined, it *won't* be present!)
Use e.g. `monodis --memberref App.mstat` to list post-trimmed members.

You can get an inkling of the "reflection metadata" that is present
by using `dotnet publish -p:IlcGenerateMetadataLog=true …`, which
produces a `.metadata.csv` file.  It's not particularly scrutible,
but can be used to verify observed behavior.  Consider one of the above
failure messages:

	The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView]

An obvious question to ask: is the `TabNavigation` property in the
reflection metadata?  Search for `"TabNavigation"` (with quotes!),
and it's *not* in there.  Compare to when this commit is in use, and:

	66087019, Property, "TabNavigation", "3410be9a 6810bea8 5410beae 5410beb2"
	3410be9a, ConstantStringValue, "TabNavigation", ""

The 3rd column is the property name `TabNavigation`, while the 2nd
column is the type; for properties, we want `Property`.  The 4th
column is "Children", one of which is:

	5410beae, MethodSemantics, "Getter : [HasThis]  Microsoft.UI.Xaml.Input.KeyboardNavigationMode get_TabNavigation()", "50086c65"

which at least verifies that `TabNavigation` is in play.

Programs can control what is contained within reflection metadata
by using string constants with Reflection APIs, for example:

	typeof(SomeKnownType).GetMethod("ConstantName")

will ensure that reflection metadata contains
`SomeKnownType.ConstantName()`, and `ConstantName()` will be returned
from `typeof(SomeKnownType).GetMethods()` and can be invoked with
`MethodInfo.Invoke()`.

If you *don't* use `typeof(SomeKnownType)` or string constants with
`Type.GetType(string)` or `type.GetMethod("constant")`, then you need
to "suggest" that some pieces of information be added to
reflection metadata.

The two predominant ways to do this are via the custom attributes:

  * [`DynamicallyAccessedMembersAttribute`][2]
  * [`DynamicDependencyAttribute`][3]

From the Uno perspective, enter `BindingPropertyHelper`: *everything*
is based on Reflection!

Fortunately NativeAOT "supports" Reflection!  (See above.)

*Unfortunately*, we now need to convince NativeAOT to store the
reflection metadata Uno requires in order to work!

Various other PRs have dealt with some of this, such as #21920.

Returning to the original failure messages, e.g.

	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView]

During the app build, `src/SourceGenerators/Uno.UI.SourceGenerators`
generates a `BindableMetadata.g.cs` file which will mention
`[Bindable]` types, e.g. for `Microsoft.UI.Xaml.Controls.FlipView`:

	/// <summary>
	/// Builder for Microsoft.UI.Xaml.Controls.FlipView
	/// </summary>
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	static class MetadataBuilder_239
	{
	  internal static global::Uno.UI.DataBinding.IBindableType Build(global::Uno.UI.DataBinding.BindableType parent)
	  {
	    var bindableType = parent ?? new global::Uno.UI.DataBinding.BindableType(151, typeof(global::Microsoft.UI.Xaml.Controls.FlipView));
	    // …
	  }
	  private static object CreateInstance() => new global::Microsoft.UI.Xaml.Controls.FlipView();
	}

`BindableMetadata.g.cs` was needed in the ye olde Xamarin world order
to tell *its* linker to e.g. "preserve the `FlipView` default ctor!"

*Now*, we can build upon this infrastructure and update `BindableType`
to request that Reflection information regarding properties, fields,
and constructors be retained.  We can do this by updating the
`BindableType` constructor:

	partial class BindableType {
	  internal const DynamicallyAccessedMemberTypes TypeRequirements =
	    DynamicallyAccessedMemberTypes.PublicProperties | …;
	  public BindableType(int estimatedPropertySize, [DynamicallyAccessedMembers(TypeRequirements)] Type sourceType) => …
	}

*Because* we have `BindableMetadata.g.cs` *and* because it provides
`typeof(FlipView)`, this directs NativeAOT to make property and other
reflection metadata available to the app, *fixing* the error messages.

Expand this addition of `[DynamicallyAccessedMembers]` to also include
`BindableProperty` and related types.

Note: the IL2111 warning "Method 'System.Type.TypeInitializer.get' …"
is *caused by* `typeof(Type)` (?!), which is particularly odd given
that we don't use `Type.TypeInitializer`!
Thanks to Alexander Köplinger for [looking into this][4].

[0]: https://learn.microsoft.comdotnet/core/deploying/native-aot
[1]: https://learn.microsoft.comdotnet/core/deploying/native-aot/#limitations-of-native-aot-deployment
[2]: https://learn.microsoft.comdotnet/api/system.diagnostics.codeanalysis.dynamicallyaccessedmembersattribute?view=net-10.0
[3]: https://learn.microsoft.comdotnet/api/system.diagnostics.codeanalysis.dynamicdependencyattribute?view=net-10.0
[4]: https://discord.com/channels/732297728826277939/732297837953679412/1445773677152174150
jonpryor added a commit to unoplatform/uno that referenced this pull request Dec 3, 2025
Context: unoplatform/uno.chefs#1712
Context: #21920
Context: unoplatform/uno.extensions#2966
Context: unoplatform/uno.extensions#2969
Context: https://discord.com/channels/732297728826277939/732297837953679412/1444909702512119899

While running the uno.chefs app on macOS under NativeAOT:

	dotnet publish -c Release -r osx-x64 -f net10.0-desktop -p:TargetFrameworkOverride=net10.0-desktop -bl \
	  Chefs/Chefs.csproj \
	  -p:SelfContained=true -p:PublishAot=true -p:IsAotCompatible=true -p:UseSkiaRendering=true \
	  -p:IlcGenerateMapFile=true -p:IlcGenerateMstatFile=true -p:IlcGenerateDgmlFile=true \
	  -p:EmitCompilerGeneratedFiles=true -p:CompilerGeneratedFilesOutputPath=`pwd`/_gen
	Chefs/bin/Release/net10.0-desktop/osx-x64/publish/Chefs

Console output would contain the following errors:

	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView]
	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [Y] property getter does not exist on type [Windows.Foundation.Point]
	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [X] property getter does not exist on type [Windows.Foundation.Point]

At this point, a description of the relation between NativeAOT and
Reflection would be useful.

*Parts* of System.Reflection can be used.  Which parts *can* be used,
and how to use them, is oddly *not* well specified in the
[Native AOT deployment][0] documentation.

What doesn't work is outlined in the [limitations][1] section:

> * No dynamic loading, for example, `Assembly.LoadFile`.
> * No run-time code generation, for example, `System.Reflection.Emit`.

What *always* appears to work is:

  * `Type.GetType()` returns a `Type` instance.

What ***can*** work is:

  * `Type.GetType(string)`, *so long as* an assembly-qualified name
    is used as a *string constant*

        // bad
        string name = GetSomeTypeName();
        Type type = Type.GetType(name);

        // good
        Type type = Type.GetType("My.Example.TypeName, ExampleAssembly");

  * `Type.GetMethod(string)`, but see fine print below.
  * `Type.GetProperty(string)`, but see fine print below.
  * `MethodInfo.Invoke()`
  * …

**The Fine Print**: in order for many Reflection-based APIs such as
`Type.GetMethod(string)` to work, the program must contain
"reflection metadata."

We can now describe, briefly, what NativeAOT does:

 1. Accept IL/assemblies as input
 2. Internally trim the IL, optimizes them, etc.
 3. Generates a native binary containing two separate bits of data:

    * Native machine code for execution
    * "reflection metadata"

You can get an inkling of what methods survived trimming and become
native code by using `dotnet publish -p:IlcGenerateMapFile=true …`,
which will produce a `.mstat` file, a PE file which references every
type and member which is in the native binary, ***after*** inlining.
(Meaning if a member is inlined, it *won't* be present!)
Use e.g. `monodis --memberref App.mstat` to list post-trimmed members.

You can get an inkling of the "reflection metadata" that is present
by using `dotnet publish -p:IlcGenerateMetadataLog=true …`, which
produces a `.metadata.csv` file.  It's not particularly scrutible,
but can be used to verify observed behavior.  Consider one of the above
failure messages:

	The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView]

An obvious question to ask: is the `TabNavigation` property in the
reflection metadata?  Search for `"TabNavigation"` (with quotes!),
and it's *not* in there.  Compare to when this commit is in use, and:

	66087019, Property, "TabNavigation", "3410be9a 6810bea8 5410beae 5410beb2"
	3410be9a, ConstantStringValue, "TabNavigation", ""

The 3rd column is the property name `TabNavigation`, while the 2nd
column is the type; for properties, we want `Property`.  The 4th
column is "Children", one of which is:

	5410beae, MethodSemantics, "Getter : [HasThis]  Microsoft.UI.Xaml.Input.KeyboardNavigationMode get_TabNavigation()", "50086c65"

which at least verifies that `TabNavigation` is in play.

Programs can control what is contained within reflection metadata
by using string constants with Reflection APIs, for example:

	typeof(SomeKnownType).GetMethod("ConstantName")

will ensure that reflection metadata contains
`SomeKnownType.ConstantName()`, and `ConstantName()` will be returned
from `typeof(SomeKnownType).GetMethods()` and can be invoked with
`MethodInfo.Invoke()`.

If you *don't* use `typeof(SomeKnownType)` or string constants with
`Type.GetType(string)` or `type.GetMethod("constant")`, then you need
to "suggest" that some pieces of information be added to
reflection metadata.

The two predominant ways to do this are via the custom attributes:

  * [`DynamicallyAccessedMembersAttribute`][2]
  * [`DynamicDependencyAttribute`][3]

From the Uno perspective, enter `BindingPropertyHelper`: *everything*
is based on Reflection!

Fortunately NativeAOT "supports" Reflection!  (See above.)

*Unfortunately*, we now need to convince NativeAOT to store the
reflection metadata Uno requires in order to work!

Various other PRs have dealt with some of this, such as #21920.

Returning to the original failure messages, e.g.

	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView]

During the app build, `src/SourceGenerators/Uno.UI.SourceGenerators`
generates a `BindableMetadata.g.cs` file which will mention
`[Bindable]` types, e.g. for `Microsoft.UI.Xaml.Controls.FlipView`:

	/// <summary>
	/// Builder for Microsoft.UI.Xaml.Controls.FlipView
	/// </summary>
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	static class MetadataBuilder_239
	{
	  internal static global::Uno.UI.DataBinding.IBindableType Build(global::Uno.UI.DataBinding.BindableType parent)
	  {
	    var bindableType = parent ?? new global::Uno.UI.DataBinding.BindableType(151, typeof(global::Microsoft.UI.Xaml.Controls.FlipView));
	    // …
	  }
	  private static object CreateInstance() => new global::Microsoft.UI.Xaml.Controls.FlipView();
	}

`BindableMetadata.g.cs` was needed in the ye olde Xamarin world order
to tell *its* linker to e.g. "preserve the `FlipView` default ctor!"

*Now*, we can build upon this infrastructure and update `BindableType`
to request that Reflection information regarding properties, fields,
and constructors be retained.  We can do this by updating the
`BindableType` constructor:

	partial class BindableType {
	  internal const DynamicallyAccessedMemberTypes TypeRequirements =
	    DynamicallyAccessedMemberTypes.PublicProperties | …;
	  public BindableType(int estimatedPropertySize, [DynamicallyAccessedMembers(TypeRequirements)] Type sourceType) => …
	}

*Because* we have `BindableMetadata.g.cs` *and* because it provides
`typeof(FlipView)`, this directs NativeAOT to make property and other
reflection metadata available to the app, *fixing* the error messages.

Expand this addition of `[DynamicallyAccessedMembers]` to also include
`BindableProperty` and related types.

Note: the IL2111 warning "Method 'System.Type.TypeInitializer.get' …"
is *caused by* `typeof(Type)` (?!), which is particularly odd given
that we don't use `Type.TypeInitializer`!
Thanks to Alexander Köplinger for [looking into this][4].

[0]: https://learn.microsoft.comdotnet/core/deploying/native-aot
[1]: https://learn.microsoft.comdotnet/core/deploying/native-aot/#limitations-of-native-aot-deployment
[2]: https://learn.microsoft.comdotnet/api/system.diagnostics.codeanalysis.dynamicallyaccessedmembersattribute?view=net-10.0
[3]: https://learn.microsoft.comdotnet/api/system.diagnostics.codeanalysis.dynamicdependencyattribute?view=net-10.0
[4]: https://discord.com/channels/732297728826277939/732297837953679412/1445773677152174150
jonpryor added a commit to unoplatform/uno that referenced this pull request Dec 4, 2025
Context: unoplatform/uno.chefs#1712
Context: #21920
Context: unoplatform/uno.extensions#2966
Context: unoplatform/uno.extensions#2969
Context: https://discord.com/channels/732297728826277939/732297837953679412/1444909702512119899

While running the uno.chefs app on macOS under NativeAOT:

	dotnet publish -c Release -r osx-x64 -f net10.0-desktop -p:TargetFrameworkOverride=net10.0-desktop -bl \
	  Chefs/Chefs.csproj \
	  -p:SelfContained=true -p:PublishAot=true -p:IsAotCompatible=true -p:UseSkiaRendering=true \
	  -p:IlcGenerateMapFile=true -p:IlcGenerateMstatFile=true -p:IlcGenerateDgmlFile=true \
	  -p:EmitCompilerGeneratedFiles=true -p:CompilerGeneratedFilesOutputPath=`pwd`/_gen
	Chefs/bin/Release/net10.0-desktop/osx-x64/publish/Chefs

Console output would contain the following errors:

	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView]
	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [Y] property getter does not exist on type [Windows.Foundation.Point]
	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [X] property getter does not exist on type [Windows.Foundation.Point]

At this point, a description of the relation between NativeAOT and
Reflection would be useful.

*Parts* of System.Reflection can be used.  Which parts *can* be used,
and how to use them, is oddly *not* well specified in the
[Native AOT deployment][0] documentation.

What doesn't work is outlined in the [limitations][1] section:

> * No dynamic loading, for example, `Assembly.LoadFile`.
> * No run-time code generation, for example, `System.Reflection.Emit`.

What *always* appears to work is:

  * `Type.GetType()` returns a `Type` instance.

What ***can*** work is:

  * `Type.GetType(string)`, *so long as* an assembly-qualified name
    is used as a *string constant*

        // bad
        string name = GetSomeTypeName();
        Type type = Type.GetType(name);

        // good
        Type type = Type.GetType("My.Example.TypeName, ExampleAssembly");

  * `Type.GetMethod(string)`, but see fine print below.
  * `Type.GetProperty(string)`, but see fine print below.
  * `MethodInfo.Invoke()`
  * …

**The Fine Print**: in order for many Reflection-based APIs such as
`Type.GetMethod(string)` to work, the program must contain
"reflection metadata."

We can now describe, briefly, what NativeAOT does:

 1. Accept IL/assemblies as input
 2. Internally trim the IL, optimizes them, etc.
 3. Generates a native binary containing two separate bits of data:

    * Native machine code for execution
    * "reflection metadata"

You can get an inkling of what methods survived trimming and become
native code by using `dotnet publish -p:IlcGenerateMstatFile=true …`,
which will produce a `.mstat` file, a PE file which references every
type and member which is in the native binary, ***after*** inlining.
(Meaning if a member is inlined, it *won't* be present!)
Use e.g. `monodis --memberref App.mstat` to list post-trimmed members.

You can get an inkling of the "reflection metadata" that is present
by using `dotnet publish -p:IlcGenerateMetadataLog=true …`, which
produces a `.metadata.csv` file.  It's not particularly scrutible,
but can be used to verify observed behavior.  Consider one of the above
failure messages:

	The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView]

An obvious question to ask: is the `TabNavigation` property in the
reflection metadata?  Search for `"TabNavigation"` (with quotes!),
and it's *not* in there.  Compare to when this commit is in use, and:

	66087019, Property, "TabNavigation", "3410be9a 6810bea8 5410beae 5410beb2"
	3410be9a, ConstantStringValue, "TabNavigation", ""

The 3rd column is the property name `TabNavigation`, while the 2nd
column is the type; for properties, we want `Property`.  The 4th
column is "Children", one of which is:

	5410beae, MethodSemantics, "Getter : [HasThis]  Microsoft.UI.Xaml.Input.KeyboardNavigationMode get_TabNavigation()", "50086c65"

which at least verifies that `TabNavigation` is in play.

Programs can control what is contained within reflection metadata
by using string constants with Reflection APIs, for example:

	typeof(SomeKnownType).GetMethod("ConstantName")

will ensure that reflection metadata contains
`SomeKnownType.ConstantName()`, and `ConstantName()` will be returned
from `typeof(SomeKnownType).GetMethods()` and can be invoked with
`MethodInfo.Invoke()`.

If you *don't* use `typeof(SomeKnownType)` or string constants with
`Type.GetType(string)` or `type.GetMethod("constant")`, then you need
to "suggest" that some pieces of information be added to
reflection metadata.

The two predominant ways to do this are via the custom attributes:

  * [`DynamicallyAccessedMembersAttribute`][2]
  * [`DynamicDependencyAttribute`][3]

From the Uno perspective, enter `BindingPropertyHelper`: *everything*
is based on Reflection!

Fortunately NativeAOT "supports" Reflection!  (See above.)

*Unfortunately*, we now need to convince NativeAOT to store the
reflection metadata Uno requires in order to work!

Various other PRs have dealt with some of this, such as #21920.

Returning to the original failure messages, e.g.

	fail: Uno.UI.Dispatching.NativeDispatcher[0]
	      The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView]

During the app build, `src/SourceGenerators/Uno.UI.SourceGenerators`
generates a `BindableMetadata.g.cs` file which will mention
`[Bindable]` types, e.g. for `Microsoft.UI.Xaml.Controls.FlipView`:

	/// <summary>
	/// Builder for Microsoft.UI.Xaml.Controls.FlipView
	/// </summary>
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	static class MetadataBuilder_239
	{
	  internal static global::Uno.UI.DataBinding.IBindableType Build(global::Uno.UI.DataBinding.BindableType parent)
	  {
	    var bindableType = parent ?? new global::Uno.UI.DataBinding.BindableType(151, typeof(global::Microsoft.UI.Xaml.Controls.FlipView));
	    // …
	  }
	  private static object CreateInstance() => new global::Microsoft.UI.Xaml.Controls.FlipView();
	}

`BindableMetadata.g.cs` was needed in the ye olde Xamarin world order
to tell *its* linker to e.g. "preserve the `FlipView` default ctor!"

*Now*, we can build upon this infrastructure and update `BindableType`
to request that Reflection information regarding properties, fields,
and constructors be retained.  We can do this by updating the
`BindableType` constructor:

	partial class BindableType {
	  internal const DynamicallyAccessedMemberTypes TypeRequirements =
	    DynamicallyAccessedMemberTypes.PublicProperties | …;
	  public BindableType(int estimatedPropertySize, [DynamicallyAccessedMembers(TypeRequirements)] Type sourceType) => …
	}

*Because* we have `BindableMetadata.g.cs` *and* because it provides
`typeof(FlipView)`, this directs NativeAOT to make property and other
reflection metadata available to the app, *fixing* the error messages.

Expand this addition of `[DynamicallyAccessedMembers]` to also include
`BindableProperty` and related types.

Note: the IL2111 warning "Method 'System.Type.TypeInitializer.get' …"
is *caused by* `typeof(Type)` (?!), which is particularly odd given
that we don't use `Type.TypeInitializer`!
Thanks to Alexander Köplinger for [looking into this][4].

[0]: https://learn.microsoft.comdotnet/core/deploying/native-aot
[1]: https://learn.microsoft.comdotnet/core/deploying/native-aot/#limitations-of-native-aot-deployment
[2]: https://learn.microsoft.comdotnet/api/system.diagnostics.codeanalysis.dynamicallyaccessedmembersattribute?view=net-10.0
[3]: https://learn.microsoft.comdotnet/api/system.diagnostics.codeanalysis.dynamicdependencyattribute?view=net-10.0
[4]: https://discord.com/channels/732297728826277939/732297837953679412/1445773677152174150
@jonpryor
jonpryor merged commit 3faa9bc into main Dec 4, 2025
@jonpryor
jonpryor deleted the dev/jonpryor/jonp-preserve-generated-bindable-props branch December 4, 2025 14:23
jonpryor added a commit that referenced this pull request Dec 22, 2025
Context: #2990
Context: #2990 (review)
Context: #2969
Context: 8870ddf

It's our favorite exercise, making uno.chefs run under NativeAOT!

	dotnet publish -c Release -r osx-x64 -f net10.0-desktop -p:TargetFrameworkOverride=net10.0-desktop -bl \
	  Chefs/Chefs.csproj \
	  -p:SelfContained=true -p:PublishAot=true -p:IsAotCompatible=true -p:UseSkiaRendering=true \
	  -p:IlcGenerateMapFile=true -p:IlcGenerateMstatFile=true -p:IlcGenerateDgmlFile=true -p:IlcGenerateMetadataLog=true \
	  -p:EmitCompilerGeneratedFiles=true -p:CompilerGeneratedFilesOutputPath=`pwd`/_gen
	Chefs/bin/Release/net10.0-desktop/osx-x64/publish/Chefs

Login to the app, click on a recipe, and no Ingredients are shown.

The app log contains messages such as:

	fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
	      The [Name] property getter does not exist on type [Chefs.Business.Models.Ingredient]

The problem is that the properties on `Ingredient` are not being
preserved.

The question: how "best" to preserve them?

As @jonpryor is the "automagic" sort, the "obvious" (and possibly
incorrect) answer is "something *outside* of uno.chefs should ensure
that the properties are preserved".

But where is `Ingredient` mentioned within uno.chefs?  What types
can be (ab)used to preserve properties?

Turns out, not too many places:

	% git grep '\<Ingredient\>'
	Chefs/Business/Models/Ingredient.cs:public record Ingredient
	Chefs/Business/Models/Ingredient.cs:    public Ingredient(IngredientData ingredientData)
	Chefs/Business/Services/Recipes/IRecipeService.cs:      ValueTask<IImmutableList<Ingredient>> GetIngredients(Guid recipeId, CancellationToken ct);
	Chefs/Business/Services/Recipes/RecipeService.cs:       public async ValueTask<IImmutableList<Ingredient>> GetIngredients(Guid recipeId, CancellationToken ct)
	Chefs/Business/Services/Recipes/RecipeService.cs:               return ingredientsData?.Select(x => new Ingredient(x)).ToImmutableList() ?? ImmutableList<Ingredient>.Empty;
	Chefs/Presentation/RecipeDetailsModel.cs:       public IListFeed<Ingredient> Ingredients => ListFeed.Async(async ct => await _recipeService.GetIngredients(Recipe.Id, ct));

The `Ingredient` type definition won't help, `IImmutableList<T>`
would be a *massive* stretch (plus we don't own it), which brings us
to `IListFeed<T>`: that *is* a type that we control!

PR #2990 explored an approach of updating `IListFeed<T>` to preserve
properties on `T`:

	partial interface IListFeed<
	  [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)]
	> {}

This approach was deemed far-reaching and undesirable.

What else can be used to preserve `Ingredient` properties?
Let's look at the *generated* code:

	% grep -ri '\<Ingredient\>' _gen
	_gen/Uno.Extensions.Reactive.Generator/Uno.Extensions.Reactive.Generator.FeedsGenerator/Chefs.Presentation.RecipeDetailsModel.Bindable.g.cs:				var ingredientsSource = (global::Uno.Extensions.Reactive.IListFeed<global::Chefs.Business.Models.Ingredient>) model.Ingredients ?? throw new NullReferenceException("The list feed property 'Ingredients' is null. Public feeds properties must be initialized in the constructor.");
	_gen/Uno.Extensions.Reactive.Generator/Uno.Extensions.Reactive.Generator.FeedsGenerator/Chefs.Presentation.RecipeDetailsModel.Bindable.g.cs:				var ingredientsSource = (global::Uno.Extensions.Reactive.IListFeed<global::Chefs.Business.Models.Ingredient>) model.Ingredients ?? throw new NullReferenceException("The list feed property 'Ingredients' is null. Public feeds properties must be initialized in the constructor.");
	_gen/Uno.Extensions.Reactive.Generator/Uno.Extensions.Reactive.Generator.FeedsGenerator/Chefs.Presentation.RecipeDetailsModel.Bindable.g.cs:		public global::Uno.Extensions.Reactive.IListFeed<global::Chefs.Business.Models.Ingredient> Ingredients { get; private set; }

The last line -- the `Ingredients` property -- is similar to
PR #2969/8870ddf4.  We could do something similar for `IListFeed<T>`
usage, and generate:

	namespace Chefs.Presentation;
	public partial class RecipeDetailsViewModel
	{
	  public Uno.Extensions.Reactive.IListFeed<Chefs.Business.Models.Ingredient> Ingredients
	  {
	    [DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(Chefs.Business.Models.Ingredient))]
	    get;
	    private set;
	  }
	}

The use of `[DynamicDependency]` ensures that the public properties
on `Ingredient` can still be accessed via Reflection, *without*
needing to modify `IListFeed<T>`itself.

Integrating this change back into uno.chefs, and now I'm able to see
Ingredients, without other changes to uno.chefs!

But!  We next see this message in the app log:

	fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
	      The [Count] property getter does not exist on type [Uno.Extensions.Reactive.Bindings.BindableListFeed`1[Chefs.Business.Models.Ingredient]]

Similar question as before: how do we preserve the properties on
`BindableListFeed<T>`?

Raising the question: where is `BindableListFeed<T>` coming from?

This was *quite* interesting, as `BindableListFeed<T>` doesn't appear
*anywhere* in uno.chefs!

	% git grep BindableListFeed
	# no source code matches
	% grep -ril BindableListFeed _gen
	# no matches

Add some printf logging to the `BindableListFeed<T>` constructors to
see how it's constructed, and:

	   at Uno.Extensions.Reactive.Bindings.BindableListFeed`1..ctor(String, IListState`1) + 0x91
	   at Uno.Extensions.Reactive.Bindings.BindableFactory.CreateList[T](String, IListState`1) + 0x2d
	   at Chefs.Presentation.RecipeDetailsViewModel..ctor(RecipeDetailsModel) + 0x333
	   at Chefs.Presentation.RecipeDetailsViewModel..ctor(Recipe recipe, INavigator navigator, IRecipeService recipeService, IUserService userService, IMessenger messenger, IShareService shareService) + 0xa0

`BindableListFeed<Ingredient>` is constructed via a
`BindableFactory.CreateList(…)` invocation within the generated
`RecipeDetailsViewModel` constructor.

Slight problem: *there is no* `BindableFactory.CreateList(…)`
invocation within the `RecipeDetailsViewModel` constructor!

	public partial class RecipeDetailsViewModel {
	  protected RecipeDetailsViewModel(global::Chefs.Presentation.RecipeDetailsModel model)
	  {
	    // …
	    if (Ingredients is null)
	    {
	      var ingredientsSource = (global::Uno.Extensions.Reactive.IListFeed<global::Chefs.Business.Models.Ingredient>) model.Ingredients ?? throw new NullReferenceException("The list feed property 'Ingredients' is null. Public feeds properties must be initialized in the constructor.");
	      var ingredientsSourceListState = ctx.GetOrCreateListState(ingredientsSource);
	      Ingredients = global::Uno.Extensions.Reactive.Bindings.BindableHelper.CreateBindableList(nameof(Ingredients), ingredientsSourceListState);
	    }
	    // …
	  }
	}

However, `BindableHelper.CreateBindableList(…)` *does* call
`BindableFactory.CreateList(…)`, so this is presumably a case of
method inlining by NativeAOT.

With that in mind, @jonpryor can think of three ways to cause the
`BindableListFeed<Ingredient>` properties to be preserved:

 1. Some form of change within FeedsGenerator, or
 2. Update `BindableFactory.CreateList<T>()` to use
    `[DynamicDependency]` to preserve the properties, or
 3. Update the `BindableListFeed<T>` constructors to have
    `[DynamicDependency]`.

The problem with (1) is that it associates types which perhaps
shouldn't be associated "like that", e.g.

	namespace Chefs.Presentation;
	public partial class RecipeDetailsViewModel
	{
	  public Uno.Extensions.Reactive.IListFeed<Chefs.Business.Models.Ingredient> Ingredients
	  {
	    [DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(Chefs.Business.Models.Ingredient))]
	    [DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(Uno.Extensions.Reactive.Bindings.BindableListFeed<>))]
	    get;
	    private set;
	  }
	}

Why should `IListFeed<Ingredient>` use dictate referencing of
`BindableListFeed<T>`?

(2) is reasonable.

The advantages to (3) is that it works, it's straightforward, and
annotation site is "close" to the site of intended effect.
(`BindableFactory.CreateList<T>()` doesn't obviously scream out
"I may require dynamic dependencies!"  The constructor doesn't either,
but at least it's on the type being impacted!)

(3) also gives us an interesting "hammer" with which to solve related
issues.  Issues such as:

	fail: Uno.UI.DataBinding.BindingPropertyHelper[0]
	      The [Count] property getter does not exist on type [Uno.Extensions.Reactive.Bindings.Collections._BindableCollection.Views.BasicView]

`BasicView` in turn is constructed via:

	   at Uno.Extensions.Reactive.Bindings.Collections._BindableCollection.Views.BasicView..ctor(CollectionFacet, CollectionChangedFacet, BindableCollectionExtendedProperties, SelectionFacet, PaginationFacet, EditionFacet) + 0x4f
	   at Uno.Extensions.Reactive.Bindings.Collections._BindableCollection.Data.LeafStrategy.CreateView(IBindableCollectionViewSource) + 0x1d4
	   at Uno.Extensions.Reactive.Bindings.Collections._BindableCollection.Data.DataLayer..ctor(DataLayer, IServiceProvider, IBindableCollectionDataLayerStrategy, IDispatcher) + 0x71
	   at Uno.Extensions.Reactive.Bindings.Collections._BindableCollection.Data.DataLayer.Create(IBindableCollectionDataLayerStrategy, IObservableCollection, IServiceProvider, IDispatcher) + 0x3e
	   at Uno.Extensions.Reactive.Dispatching.DispatcherLocal`1.GetValueCore(IDispatcher, IDispatcher) + 0x285
	   at Uno.Extensions.Reactive.Dispatching.DispatcherLocal`1.GetValue(IDispatcher) + 0x3f
	   at Uno.Extensions.Reactive.Bindings.BindableListFeed`1.<Uno-Extensions-Reactive-ISignal<Uno-Extensions-Reactive-IMessage>-GetSource>d__66.MoveNext() + 0xb1
	   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine&) + 0x4d
	   at Uno.Extensions.Reactive.Bindings.BindableListFeed`1.<Uno-Extensions-Reactive-ISignal<Uno-Extensions-Reactive-IMessage>-GetSource>d__66.System.Collections.Generic.IAsyncEnumerator<Uno.Extensions.Reactive.IMessage>.MoveNextAsync() + 0x46
	   at Uno.Extensions.Reactive.Utils.FeedUIHelper.<MoveNext>d__4`1.MoveNext() + 0x115
	   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine&) + 0x4d
	   at Uno.Extensions.Reactive.Utils.FeedUIHelper.MoveNext[T](IAsyncEnumerator`1, CancellationToken) + 0x82
	   at Uno.Extensions.Reactive.Utils.FeedUIHelper.<GetSource>d__0.MoveNext() + 0x227
	   at System.Threading.ExecutionContext.RunInternal(ExecutionContext, ContextCallback, Object) + 0x89
	   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.MoveNext(Thread) + 0x57
	   at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(IAsyncStateMachineBox, Boolean) + 0x52
	   at System.Threading.Tasks.Task.RunContinuations(Object) + 0x4f
	   at System.Threading.Tasks.Task`1.TrySetResult(TResult) + 0x8e
	   at System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1.SetResult(TResult) + 0x29
	   at Uno.Extensions.Reactive.Utils.FeedUIHelper.<GetSourceEnumerator>d__3`1.MoveNext() + 0x284
	   at System.Threading.ExecutionContext.RunInternal(ExecutionContext, ContextCallback, Object) + 0x89

i.e. "nowhere" near `*.Presentation` logic, and yet its properties
are used by XAML.

Regardless, if it's constructed, we *probably* need its properties, so:
add `[DynamicDependency]` to the `BasicView` constructor!  The message
is fixed.  (This is a fascinating hammer, ripe for abuse.)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants