dotnet / wpf

WPF is a .NET Core UI framework for building Windows desktop applications.
MIT License
7.03k stars 1.16k forks source link

API Request: Allow developers to inject a XAML factory for creating objects #4022

Open lindexi opened 3 years ago

lindexi commented 3 years ago

As we know, the WPF will call the XamlTypeInvoker.CreateInstance to create the object in the XAML engine.

https://github.com/dotnet/wpf/blob/bbd9e44d87b4edd8880f4c09c6db36a2f3e23ba8/src/Microsoft.DotNet.Wpf/src/System.Xaml/System/Xaml/Schema/XamlTypeInvoker.cs#L133-L145

All the type which we define will use reflection to create. I do not think this is a high-performance behavior.

Should we add XAML object creation factory that allow developers to inject a XAML factory for creating objects?

            // Before the XAML engine starts, add initialization logic
            XamlObjectCreationFactory.RegisterCreator(() => new MainWindow());

In the future, we can use SourceGenerator to automate the writing of this part of the code

batzen commented 3 years ago

How would this work during design time? It would also be very bad if regular object creation gets slower, in case no creator is registered.

Aren't the XamlTypeInvoker instances cached somewhere? If that's the case your benchmark does not reflect real world usage as you ignore the cache for the "old" XamlTypeInvoker and use the new cache for the "new" XamlTypeInvoker.

lindexi commented 3 years ago

How would this work during design time? It would also be very bad if regular object creation gets slower, in case no creator is registered.

Aren't the XamlTypeInvoker instances cached somewhere? If that's the case your benchmark does not reflect real world usage as you ignore the cache for the "old" XamlTypeInvoker and use the new cache for the "new" XamlTypeInvoker.

How would this work during design time? NO

It would also be very bad if regular object creation gets slower, in case no creator is registered. NO

Aren't the XamlTypeInvoker instances cached somewhere? Yes, it cached in WPFXamlType

Thank you.

lindexi commented 3 years ago

@batzen I just replace reflection creation with Func<object> creation.

lindexi commented 3 years ago

See https://github.com/dotnet/wpf/issues/499 https://github.com/dotnet/wpf/issues/4461