Reflection is bad because:
1) it's really, really slow
2) it bloats the code size for AOT-only scenarios
3) it adds the need to add hints/configuration for IL linker in AOT scenarios
I'd like to completely remove reflection usage from Avalonia. We should be able to run with CoreRT without additional .rd.xml files and with these compatibility flags disabled.
Right now our users of reflection are:
1) Portable.Xaml (will be fixed by XamlIl)
2) Bindings
3) Style selector parsers (will be fixed by XamlIl)
4) Weak event managers (the new one can be fixed by IL-rewriting build-task )
There are two problems with bindings that we need to solve:
1) If we want to have them compiled, we need to know the type of DataContext in advance. So we might need to add some kind of XAML directive (e. g. DataContextType="{x:Type myNs:MyType}") for specifying the data context type when it can't be determined from DataType or from binding from the parent DataContext. That would be most likely required for top-level XAML element only.
2) We have IStreamPlugin extension point which isn't strongly typed and is resolved in runtime. We need to make it to somehow work at compile time.
While we are working on these, new features get added, so when adding a new feature that needs type information, provide a way for it to work at compile time.
I think implementing compile-time bindings would be great. I had some experience lately with x:Bind in UWP and while it has its issues, it's very appealing. It also significantly reduces the need for converters, as the binding expression is converted to a C# method, and so can include method calls, casts, etc.
The data context problem was solved by changing the binding context to the class the XAML file is attached to, and you'd usually have one or more strongly-typed properties in it (e.g. ViewModel), instead of the DataContext. For DataTemplates, the DataType is used.
Code is generated at design/compile time. I'm not sure if MS intends on open-sourcing the x:Bind implementation (it's a part of the XAML MSBuild tasks, but only in UWP.) Perhaps it's worth asking.
Not directly related to Avalonia but this https://github.com/neuecc/Utf8Json can build serializers at build time and eliminate reflection. Just thought it might be useful and was worth recording somewhere.
Just found this issue, maybe the new source generators coming with .net 5 can be helpful to eliminate reflection usage? https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/
@Mrxx99 we aren't planning to drop F# support. Source generators will be used for generating fields for x:Name, however.
Apparently Tmds.DBus uses System.Reflection.Emit in their implementation. I've opened an issue there for a source-generated backend: https://github.com/tmds/Tmds.DBus/issues/79
Most helpful comment
@Mrxx99 we aren't planning to drop F# support. Source generators will be used for generating fields for
x:Name, however.