Repository navigation
Implement Lazy ResourceDictionary for SourceGen (~8x faster inflation) - #33826
Conversation
7b7fd52 to
53b59db
Compare
There was a problem hiding this comment.
Pull request overview
This PR implements lazy resource creation in ResourceDictionary via factory functions, enabling on-demand instantiation of resources to improve XAML inflation performance and adding support for x:Shared="false" functionality.
Changes:
- Adds
AddFactoryAPI to ResourceDictionary for lazy resource creation with shared/non-shared semantics - Implements SourceGen integration to emit AddFactory calls for LazyRD-enabled XAML files
- Refactors resource change propagation to use keys instead of values to avoid premature lazy resource resolution
- Adds x:Shared attribute support (SourceGen only) with runtime/XamlC throwing appropriate errors
Reviewed changes
Copilot reviewed 38 out of 38 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| src/Controls/src/Core/ResourceDictionary.cs | AddFactory API, LazyResource wrapper class, resolve-on-access logic, diagnostic support |
| src/Controls/src/Core/ResourcesChangedEventArgs.cs | Key-based resource change propagation to avoid resolving lazy resources |
| src/Controls/src/Core/Element/Element.cs | OnResourcesChangedKeys methods for lazy-aware resource propagation |
| src/Controls/src/SourceGen/ProjectItem.cs | LazyRD property (feature flag with default=true) |
| src/Controls/src/SourceGen/NodeSGExtensions.cs | IsLazyResource detection logic with value type/string exclusions |
| src/Controls/src/SourceGen/SetPropertyHelpers.cs | AddLazyResourceToResourceDictionary emits AddFactory lambdas |
| src/Controls/src/SourceGen/Visitors/*.cs | Visitor changes to skip lazy resources and emit AddFactory calls |
| src/Controls/src/SourceGen/KnownMarkups.cs | StaticResource resolution for lazy resources in lambda contexts |
| src/Controls/src/Xaml/*.cs | x:Shared XML name parsing and runtime error handling |
| src/Controls/src/Build.Tasks/*.cs | XamlC error for x:Shared usage |
| src/Controls/tests/Core.UnitTests/ResourceDictionaryTests.cs | Comprehensive AddFactory API tests including known issues documentation |
| src/Controls/tests/Xaml.UnitTests/Issues/.xaml | XShared and LazyResourceDictionary test files |
| src/Controls/tests/Xaml.UnitTests/Benchmark*.xaml* | Benchmark tests with LazyRD diagnostics |
| docs/lazy-resourcedictionary-spec.md | Comprehensive specification document |
| PublicAPI.Unshipped.txt | New public API surface for AddFactory and ResourcesChangedEventArgs |
| Microsoft.Maui.Controls.Common.targets | MSBuild integration for LazyRD metadata |
53b59db to
4fed830
Compare
559f558 to
13395e8
Compare
Dependency NoteDuring testing of this PR, a pre-existing SourceGen bug was discovered where typed bindings for This bug is NOT caused by lazy ResourceDictionary - it reproduces on main branch with SourceGen enabled. The fix has been extracted to a separate PR: #33914 This PR should be rebased on top of #33914 once it's merged. |
|
/azp run |
|
Azure Pipelines successfully started running 3 pipeline(s). |
64b484a to
c7106b0
Compare
|
/azp run |
|
Azure Pipelines successfully started running 3 pipeline(s). |
|
/azp run |
|
Azure Pipelines successfully started running 3 pipeline(s). |
ec87011 to
4793ee7
Compare
4ab6b81 to
8b7edc6
Compare
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 33826Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 33826" |
8b7edc6 to
0a0edfe
Compare
Add lazy resource instantiation to XAML SourceGen for significant performance improvements. Resources are now created on-demand via factory functions instead of upfront instantiation. - AddFactory API on ResourceDictionary for lazy resource registration - x:Shared="false" support - each access creates a new instance - Keys-only resource propagation to prevent premature resolution - Lazy-friendly ValuesChanged event with on-demand value lookup | Method | Mean | Ratio | Allocated | Alloc Ratio | |--------|------|-------|-----------|-------------| | XamlC (baseline) | 336.88 µs | 1.00 | 352.97 KB | 1.00 | | SourceGen LazyRD | 43.17 µs | 0.14 | 60.14 KB | 0.17 | - **~8x faster** than XamlC - **~6x less memory** allocated - 88% of resources remain unresolved (created only when accessed) - Value types (no benefit - copied on access) - Strings (need TypeConverter processing) - Styles with Class attribute (need Add() for class style list) - Items with x:Name (need variable for field assignment) LazyRD is enabled by default. To disable per-file: <MauiXaml Update="file.xaml" LazyRD="false" /> Or globally: <MauiXamlLazyRD>false</MauiXamlLazyRD>
- Add null check in StaticResourceExtension.CastTo to handle null values from lazy resource factories - Add OnParentResourcesChangedKeys overrides to VisualElement for proper key-based resource propagation filtering - Update test to reflect correct lazy resource resolution behavior Fixes crash when navigating to ProjectDetailPage in MAUI template with SourceGen enabled.
When a markup extension (like InvertedBoolConverter) is stored as a lazy resource in ResourceDictionary, the factory stores the result of ProvideValue() (e.g., ICommunityToolkitValueConverter), not the original type (InvertedBoolConverter). The source generator was incorrectly casting to the original type when looking up the lazy resource, causing an InvalidCastException at runtime. This fix checks if the lazy resource type implements IMarkupExtension<T> and uses the return type T instead of the original declaring type for the cast expression.
GetDiagnostics() and ResourceDiagnostics are only available in Debug builds (#if DEBUG in ResourceDictionary.cs). The Benchmark tests that use these APIs must also be conditionally compiled.
Add SetNamescopesAndRegisterNamesVisitor and SetResourcesVisitor to the lazy resource lambda body in AddLazyResourceToResourceDictionary(), matching the established DataTemplate pattern. Without these visitors, x:Reference inside lazy resources (e.g. DataTemplates or Styles in ResourceDictionary) could not resolve names from the outer scope, causing MAUIG1001 errors.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
db87466 to
f3a2e1e
Compare
|
/azp run maui-pr-devicetests, maui-pr-uitests |
|
Azure Pipelines successfully started running 2 pipeline(s). |
The BOM-prefixed #nullable enable line was sorted to the bottom of the file instead of remaining at line 1, causing RS0017 analyzer errors. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
|
/azp run maui-pr-devicetests, maui-pr-uitests |
|
Azure Pipelines successfully started running 2 pipeline(s). |
Note
Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!
Summary
Add lazy resource instantiation to XAML SourceGen. Instead of inflating all Styles, Brushes, and other ResourceDictionary entries upfront, resources are now registered as factory functions and inflated on-demand only when accessed.
Fixes #28985
How It Works
Before: All resources created during page initialization, even if never used.
After: Resources stored as
Func<object>factories, inflated only when accessed viaStaticResource,DynamicResource, or code.Performance Results
Benchmark with 63 resources (colors, brushes, styles):
Key Metrics
Features
AddFactoryAPI on ResourceDictionary for lazy resource registrationx:Shared="false"support - each access creates a new instance (fixes crashes with sharedStrokeShape)ValuesChangedevent - uses keys + resolver for on-demand value lookupExclusions from Lazy (inflated normally)
ClassattributeAdd()for class style listx:NameConfiguration
LazyRD is enabled by default. To opt-out:
Testing