You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
↑ Core 1,157 tests pass under dotnet test and xunit.console. Controls 7,467 pass, 30 skipped. ↑ 5 of the new or affected tests fail with main's activation code. The Hot Reload test fails under xunit.console without the FullName fix. ↑ The review-reported singleton regression is fixed; its test fails without the fix. Mutation checks confirm the custom-factory fallback and no-retry tests. ↑ An Android device test of per-context Context and dependency capture passes 2/2 on an API 35 emulator and fails if the application context is substituted. ↑ Controls.Core compiles for Android, iOS and MacCatalyst. An independent code review found no issues. ↓ Controls.Core platform compiles ran on an earlier head; later commits change only a lifetime check and tests. ↓ iOS, Mac Catalyst and Windows device tests were not run. ↓ CI has not run on this head.
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!
Target Branch
This PR is for
Initial base
New features, API changes, or .NET 12 work (including .NET 12 fixes)
main
.NET 11 servicing fixes
net11, for review
Older servicing, release integration, infrastructure, or documentation
For .NET 11 fixes, only a maintainer retargets the approved PR to the active
inflight lane and merges it after CI validates that final base. Do not merge
individual fixes directly into net11; agents must not retarget or merge.
Description of Change
This is layer 1 of 5 in a stack that splits #29952 ("[trimming] Trimmable element handlers") into reviewable pieces. It is based on main at 04d36966ed9d334c056872d83741e973d61f6c55.
This PR: context-aware handler activation and a Hot Reload fix.
Mapper infrastructure that preserves customizations: framework cells in PropertyMapper/CommandMapper, sequenced customizations, the *ForControls helpers and WithFrameworkMappingsSealed. Controls remaps switch to the helpers but still run eagerly at UseMauiApp.
Lazy Controls remapping: OneTimeInitializationAction, IControlsMapperRemappable, per-type RemapForControls and the attach hooks. The DI default table is still present.
[trimming] Trimmable element handlers #29952 itself, rebuilt on layer 3: [ElementHandler] attributes, removal of the eager DI default table, resolution precedence and versioned caches.
Construction moves into the factory.ElementExtensions.ToHandler no longer catches MissingMethodException, and no longer records the view type in a process-wide handlersWithConstructors set. It calls the internal MauiHandlersFactory.GetHandlerWithInjection instead.
The old set leaked across apps and contexts. After one app needed injection for a view type, every later app took the injection path for that type, even when it had registered a factory for it.
MauiFactory.CreateInstance becomes a protected virtual activation hook.MauiHandlersFactory overrides it for type-based handler registrations reached through ToHandler():
A public parameterless constructor is used when present. Value-type handlers keep their default construction.
Otherwise ActivatorUtilities.CreateInstance resolves constructor arguments from the current IMauiContext services, including the Android Context. No missing-constructor exception is thrown first.
A dependency failure propagates and the activation is not retried.
A singleton registration whose handler needs injection is never cached: as before, its activation falls back to creating a new handler from the current context on every request. A singleton with a parameterless constructor is cached as on main.
Unchanged paths:
Factory registrations still receive the current IMauiContext and run on every request.
Direct GetHandler(Type) callers keep the parameterless-constructor-only behavior.
Custom IMauiHandlersFactory implementations keep the exception-based fallback. It applies to MissingMethodException and to a HandlerNotFoundException that wraps one.
Main's resolution order and caching are kept as they are: _serviceCache, RegisteredHandlerServiceTypeSet, and the internal ElementHandlerAttribute<THandler> path.
The eager Controls AddControlsHandlers registrations are untouched, including the Android ListView, TableView and Frame context factory lambdas.
Hot Reload
MauiHotReloadHelper.RegisterHandlerReplacement now matches registered handler types by FullName. It no longer resolves the name through AppDomain assemblies, which returns a different Type when an assembly is loaded twice. xunit.console, the runner used in CI, loads the test assembly twice.
Injected handlers are created through the factory's GetService path, so their types are now recorded and Hot Reload replacement applies to them.
Tests and docs
Core HostBuilderHandlerTests gain activation tests covering:
injection from the current context, and factory overrides taking precedence;
no retry after a dependency failure, including a HandlerNotFoundException wrapping a MissingMethodException;
preference for the parameterless constructor;
value-type handlers;
no first-chance MissingMethodException;
isolation between apps;
Hot Reload replacement after injection;
a singleton registration that needs injection, across two elements and two contexts;
the custom-factory fallback for a HandlerNotFoundException wrapping a MissingMethodException (injects) or an unrelated exception (propagates without GetHandlerType).
An Android device test (src/Core/tests/DeviceTests/HandlerActivationTests.Android.cs) activates an injected handler through ToHandler with two MauiContexts wrapping distinct Android contexts, for transient and singleton registrations, and asserts each handler captures its own Context and dependency.
The unit tests are the registration-based forms of the [trimming] Trimmable element handlers #29952 tests. The attribute-based variants need layer 4's non-generic ElementHandlerAttribute, and C# 11 generic attributes are not available in the test project.
docs/design/HandlerResolution.md gains a "Handler Instantiation" section and an updated MauiFactory bullet. Both describe only this layer's behavior.
Deferred to layer 4: the attribute-specific constructor diagnostic ("handlers declared with ElementHandlerAttribute must have a public parameterless constructor…"). On main, the attribute requires THandler : new(), so that error cannot occur here.
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Core -Platform android -DeviceUdid emulator-5556 -TestFilter "Category=MauiContext" -IncludeClasses "Microsoft.Maui.DeviceTests.HandlerActivationTests" on an API 35 emulator — passed, 2/2.
Platform compiles below ran on head f1b80314ab; later commits only add a lifetime check in MauiHandlersFactory.cs and tests. dotnet build src/Controls/src/Core/Controls.Core.csproj -f <tfm> -c Release --disable-build-servers -nodeReuse:false -v:q, run after building Microsoft.Maui.BuildTasks.slnf — passed, 0 errors:
net12.0-android37.0: the first build reported 1 warning, not captured. A rebuild after touching MauiHandlersFactory.cs reported none.
net12.0-ios27.1 and net12.0-maccatalyst27.0: 0 warnings.
With main's src/Core/src restored, 5 HostBuilderHandlerTests fail: ConstructorInjectionDoesNotAffectOtherApps, ConstructorInjectionFailureIsNotRetried, ConstructorInjectionUsesCurrentContextAndHonorsFactoryOverrides, ToHandlerPrefersParameterlessConstructorWhenInjectionIsAlsoAvailable, and the existing HandlerCollectionFactoriesReceiveTheCurrentMauiContext. The last one is polluted by main's process-wide set.
With only the HotReloadHelper change reverted, HotReloadReplacesHandlerAfterConstructorInjection fails under xunit.console.
Without the singleton-lifetime check, SingletonRegistrationRequiringInjectionCreatesHandlerPerActivation fails. Removing the wrapped-exception fallback fails CustomHandlersFactoryWrappedMissingConstructorFallsBackToInjection; broadening it to any inner exception fails CustomHandlersFactoryWrappedUnrelatedExceptionPropagates. Dropping ConstructorInjectionAttempted from that catch fails WrappedMissingConstructorFromInjectedDependencyIsNotRetried.
Passing mauiContext.Context.ApplicationContext instead of the current Android context fails both device-test cases.
Not run: iOS, Mac Catalyst and Windows device tests, and Windows builds.
Issues Fixed
Part of #29952; supports the trimmable handler work started in #28357.
ElementExtensions.ToHandler now delegates construction to the handler
factory instead of catching MissingMethodException and remembering view
types in a process-wide set. MauiFactory exposes a virtual activation
hook; MauiHandlersFactory prefers a public parameterless constructor
(or default construction for value types) and otherwise uses
ActivatorUtilities with the current IMauiContext services, including the
Android Context. Dependency failures propagate without retrying, factory
registrations keep receiving the current context, and custom
IMauiHandlersFactory implementations keep the exception-based fallback.
Hot Reload handler replacement matches registered handler types by
full name, so a test assembly loaded twice (xunit.console) no longer
prevents replacement; injected handlers are recorded like other
activated handlers.
This is layer 1 of the stack splitting #29952.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
The changes can cache and reuse injected handlers across elements and contexts, breaking handler ownership and dependency isolation, while the wrapped-exception fallback lacks regression coverage.
This PR prepares .NET MAUI’s handler infrastructure for the trimmable-handler stack by moving context-aware activation into the factory and fixing Hot Reload matching across duplicate assembly loads.
Changes:
Moves constructor injection into factory activation and removes the process-wide injection tracking set.
Matches Hot Reload handler replacements by full type name.
Adds activation regression tests and documents construction behavior.
MauiFactory retains singleton instances. Activating a handler that
needs constructor injection inside GetService() would cache it for a
singleton descriptor, so every element and context would share the
first handler and its dependencies. Singleton registrations now keep
the base activation and the MissingMethodException fallback, which
creates a new handler from the current context on each request, as
before.
Add regression tests for two elements and two contexts, and for the
custom IMauiHandlersFactory fallback on a HandlerNotFoundException that
wraps a MissingMethodException or an unrelated exception.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
The activation tests do not exercise the Android branch, leaving native Context forwarding and DI resolution across distinct MauiContexts without the requested device regression coverage.
No open issues 🎉
1 previously missed issue
In code that hasn't changed since last review
Add Android regression test for handler context forwarding
The added activation tests run in the platform-neutral Core.UnitTests project, so they never exercise this Android branch. Please add an Android device regression test that registers a handler without a parameterless constructor, accepts an Android Context plus a DI dependency, and activates it through ToHandler with two distinct MauiContexts. Assert that each handler receives its own context and dependency; the current tests would remain green if native Context forwarding were removed or used the app-wide context instead.
Add a unit test where an injected dependency throws a
HandlerNotFoundException wrapping MissingMethodException: the same
exception propagates and the dependency factory runs once. Add an
Android device test that activates an injected handler through
ToHandler with two MauiContexts wrapping distinct Android contexts, for
transient and singleton registrations, and asserts each handler
captures its own context and dependency.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
GPT-6.2 Sol: Run the full UI suite on all four platforms because shared handler activation affects every control category. MAI Code 2: Shared handler activation and Hot Reload changes; runs the complete Controls and Core device tests on every platform.
🧪 Ran — 77 categories on Android, iOS, MacCatalyst, Windows
The complete maui-pr-uitests suite runs on every platform (same as /azp run).
📊 Results — failed: 95 passed, 3 failed of 98 jobs
GPT-6.2 Sol: Run Controls and Core device tests on all four platforms, including the new Android context-injection regression test. MAI Code 2: Shared handler activation and Hot Reload changes; runs the complete Controls and Core device tests on every platform.
🧪 Ran — 102 categories on Android, iOS, MacCatalyst, Windows
A root replacement started from the assignment's PropertyChanging animates once its own page lands .A root replacement started from the assignment's PropertyChanging animates once its own page lands (UIKit)
Categories not run:Graphics, Essentials, BlazorWebView
Each skipped platform and project is listed as a maui-pr-devicetests (skipped) … status on this commit. Use /azp run maui-pr-devicetests for the full suite.
🤖 Why these tests — AI rationale (GPT-6.2 Sol + MAI Code 2)
UI tests
Each model chose independently; every test that runs was selected by at least one of them.
Platform
GPT-6.2 Sol
MAI Code 2
Android
all categories
all categories
iOS
all categories
all categories
MacCatalyst
all categories
all categories
Windows
all categories
all categories
GPT-6.2 Sol — Run the full UI suite on all four platforms because shared handler activation affects every control category.
ElementExtensions.ToHandler now delegates activation to MauiHandlersFactory on every platform, so no standard UI category can be ruled out.
HotReloadHelper changes handler replacement; no Material3-specific styling changed.
MAI Code 2 — Shared handler activation and Hot Reload changes; runs the complete Controls and Core device tests on every platform.
MauiFactory, MauiHandlersFactory, and ElementExtensions change shared handler construction, affecting controls regardless of platform.
MauiContext-specific dependency resolution and the Hot Reload handler replacement path span the UI application's handler infrastructure.
A full UI run is warranted because these changes affect base handler activation rather than one control category.
Documentation and unit-test-only additions do not narrow the runtime coverage required.
Device tests
Each model chose independently; every test that runs was selected by at least one of them.
GPT-6.2 Sol — Run Controls and Core device tests on all four platforms, including the new Android context-injection regression test.
MauiHandlersFactory and ToHandler affect Controls and Core handler creation on all four platforms.
HandlerActivationTests.Android.cs adds Core.MauiContext coverage for Android context injection.
No separate Graphics, Essentials, or BlazorWebView changes warrant those projects.
MAI Code 2 — Shared handler activation and Hot Reload changes; runs the complete Controls and Core device tests on every platform.
MauiFactory and MauiHandlersFactory activation changes apply broadly to Core and Controls handler creation.
The added Android device test requires Core.MauiContext coverage on Android, while the production path is shared across platforms.
The full Controls and Core projects cover context-aware construction, Hot Reload integration, and handler consumers without adding unrelated Graphics, Essentials, or BlazorWebView projects.
Generated by /review run-tests. A targeted run is a fast signal, not full-suite certification.
The reason will be displayed to describe this comment to others. Learn more.
[moderate] Regression Prevention and Test Coverage - The replacement-matching change has no discriminating negative test for an unrelated registered handler. HotReloadReplacesHandlerAfterConstructorInjection registers only the handler being replaced, and the existing pending-replacement tests likewise register only their target. Broadening this predicate to accept every non-null registered handler type would therefore satisfy their assertions while replacing unrelated controls' handlers in an app with multiple registrations. Register and activate a second handler with a different FullName, replace the first, and assert that the second registration and subsequent activation remain unchanged.
<!-- copilot-assessment:v1 -->
### Agent assessment
Self-reported assessment, not an independent review.
Assessed revision: `df9d3fbacadf4ad80a64e21167e3032349618b8a`
| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8/10 | ↑ Core 1,233 tests pass under `dotnet test`
and xunit.console. Ten consecutive full Core runs passed before the
rebase onto #40721's latest commit. Controls 7,467 pass, 30
skipped.<br>↑ Every regression test added in review fails on the commit
before its fix, and the inherited-key wrapper tests overflow the stack
there.<br>↑ Controls.Core compiles for Android, iOS and MacCatalyst.
Core builds with 0 warnings.<br>↓ Three review findings are declined and
documented: concurrent customization, and untracked parent changes.<br>↓
Windows was not compiled locally and no device tests were run.<br>↓ CI
has not run on this head. |
<!-- /copilot-assessment -->
<!-- Please let the below note in for people that find this PR -->
> [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!
<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->
### Target Branch
| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |
- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).
For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.
### Description of Change
This is **layer 2 of 5** in a stack that splits #29952 ("[net12.0]
Trimmable element handlers") into reviewable pieces. It is stacked on
#40721 (base branch `simonrozsival-handlers-stack-l1-activation`), and
the stack ultimately targets `main` (.NET 12).
1. #40721: context-aware handler activation and a Hot Reload `FullName`
fix.
2. **This PR: mapper infrastructure that preserves customizations.**
Controls remaps still run eagerly.
3. Lazy Controls remapping: `OneTimeInitializationAction`,
`IControlsMapperRemappable`, per-type `RemapForControls` and the attach
hooks. The DI default table is still present.
4. #29952 itself, rebuilt on layer 3: `[ElementHandler]` attributes,
removal of the eager DI default table, resolution precedence and
versioned caches.
5. The Copilot guidance PR #40715.
This layer makes the order in which framework remaps and app
customizations run irrelevant for sealed mappers. Layer 3 relies on that
when it makes the remaps lazy. On its own, this layer behaves like main
for apps that customize mappers after `UseMauiApp`.
#### `PropertyMapper` / `CommandMapper`
- **Framework cells.** The internal `SealFrameworkMappings()` /
`WithFrameworkMappingsSealed()` marks the mappings added so far as
built-in. Each one is held in a cell whose delegate never changes.
`ModifyFrameworkMapping` updates the cell in place, so delegates the app
obtained earlier still include later framework remaps.
- **Sequenced customizations.** The new global
`MappingCustomizationSequence` orders every app customization across all
mappers.
- Each customized key gets a `MappingCustomization` record: the
framework layer plus the customizations in order.
- An indexer assignment is recorded as a customization when it replaces
an existing key, or when the mapper is sealed. It then composes on top
of framework remaps instead of being overwritten by them.
- **As-of lookups.** `GetProperty` / `GetCommand` and the typed indexers
return a mapping as of the current sequence. It includes later framework
remaps but not later app customizations, so `var previous = mapper[key];
mapper[key] = (h, v) => { previous(h, v); ... };` cannot recurse into
itself.
- **Chained keys.** A customization of a key the mapper inherits from a
chained parent captures the parent's app customizations recorded up to
that point, as before. The parent's framework mappings and remaps are
always observed.
- **Invalidation.** `ChainVersion` sums the versions of a mapper and its
chain. Merged views and compositions are rebuilt when any mapper in the
chain changes.
- **Overrides.** Subclasses that override `GetProperty` / `GetCommand`
are honored when a record is created.
#### Extensions
- The public `AppendToMapping`, `PrependToMapping`, `ModifyMapping` and
`ReplaceMapping` helpers for both mappers are routed through the
customization records. Mappers that are not `PropertyMapper` /
`CommandMapper` keep the old capture-and-add path.
- New internal `ReplaceMappingForControls`, `ModifyMappingForControls`,
`AppendToMappingForControls` and `PrependToMappingForControls` helpers
modify the framework layer instead. Their typed overloads fall through
to the previous mapping when the handler or view type doesn't match.
#### Built-in mappers and Controls remaps
- The built-in Core handler mappers that Controls remaps call
`.WithFrameworkMappingsSealed()`. That includes `ViewHandler.ViewMapper`
/ `ViewCommandMapper` and the Entry, Editor and SearchBar command
mappers.
- The Controls `*.Mapper.cs` remaps switch from the public helpers to
the `*ForControls` helpers. Otherwise they are unchanged:
- They still run eagerly from `UseMauiApp`
(`AppHostBuilderExtensions.RemapForControls`).
- `Element` / `VisualElement` still run theirs through
`RemappingHelper`, and `Label` / `Switch` through their static
constructors.
- `Label` keeps the public `AppendToMapping` for Android
`IsTextSelectable` and Apple `FlowDirection`, as in #29952.
#### Behavior changes
These are also documented, with migration guidance, under "Behavior
changes" in `docs/design/HandlerResolution.md`.
- **App customizations registered before a Controls remap now compose on
top of it.** This affects sealed mappers, for customizations registered
before `UseMauiApp`, for example from a handler's static constructor. It
matches what main already does for customizations registered after
`UseMauiApp`.
- Callbacks appended to two related keys can run in a different order.
Example: app callbacks on `StepperHandler.Mapper` `Increment` and
`Interval`. Changing `Increment` used to run the app's `Increment`
callback before the Controls redirect to `Interval`; it now runs it
after the `Interval` callback.
- *Migration:* don't rely on callback order across keys. Read the value
from the virtual view, or update the dependent native state in the
callback.
- This is the intended .NET 12 behavior, so there is no runtime opt-out.
- **Inherited mappings of sealed built-in mappers are bound to that
mapper.** On a mapper such as `LabelHandler.Mapper`,
`GetProperty`/`GetCommand` and the indexers return a child-bound mapping
for keys inherited from `ViewHandler.ViewMapper`, not the `ViewMapper`
delegate itself.
- The returned mapping also observes a later framework remap of the key
on that mapper.
- Invoking or wrapping it behaves as before. Comparing it by reference
does not.
- Internal lookups still resolve the chained mapping directly, including
the animation transform check.
- **Unchanged from main:**
- A Controls remap of an inherited key, such as iOS
`FlyoutViewHandler.Mapper` `FlowDirection`, builds on the parent mapping
as of the remap. App customizations of `ViewMapper` registered before
`UseMauiApp` therefore still run for `FlyoutPage`.
- A customized key keeps the chained mappers it was recorded with when
`Chained` is later replaced or cleared.
#### Review fixes (7dd2952)
- Wrapping an inherited key on an unsealed mapper, e.g. `var previous =
child[key]; child[key] = (h, v) => previous(h, v);`, no longer recurses
infinitely. This applies to both mappers, including the inherited
`Focus` command on `ButtonHandler.CommandMapper`.
- Each mapper change now takes a stamp from a shared monotonic counter,
instead of the chain version being a sum. Replacing a chained mapper
with one that changed less often now refreshes merged views and
compositions.
- Each customization registers an index-bound mapping through
`SetPropertyCore`, so:
- `GetProperty`/`GetCommand` don't allocate for customized keys, which
matters on the animation path;
- transformations made by a `SetPropertyCore` override apply to
customized keys.
- Compositions are rebuilt when another thread records a customization
while they are being composed.
#### Review fixes (df9d3fb)
- A direct replacement through `Add` or the indexer applies an
overridden `SetPropertyCore` transformation once, not twice.
- The typed public `ModifyMapping` overload, and the
`AppendToMapping`/`PrependToMapping` overloads built on it, map virtual
views of another type through the mapper's current `Chained`, as `Add`
does.
- The mapper tests' allocation and identity checks tolerate
customizations recorded by tests running in parallel.
- `HandlerResolution.md` documents that mapper customization is a
startup operation, and how a child observes untracked parent changes:
first assignments on unsealed mappers, and parents that aren't
`PropertyMapper`/`CommandMapper`.
#### Tests and docs
- Core `PropertyMapperExtensionTests` and `CommandMapperExtensionTests`
gain tests covering:
- framework remaps under earlier appends, prepends, modifications and
replacements;
- post-seal assignments, including keys that don't exist yet;
- chained capture semantics;
- cached `GetProperty` / `GetCommand` and indexer wrappers;
- `GetProperty` / `GetCommand` overrides;
- regression tests for each review fix: inherited-key wrappers, chain
replacement, allocation-free lookups, `SetPropertyCore` override
transformations and parent customizations under child remaps;
- fall-through tests for the typed helpers, with a mismatched view and
with an incompatible non-null handler.
- `StoryboardTests` now removes the recorded `Scale` customization when
it restores `ViewMapper`, so later tests see the original mapping.
- `docs/design/HandlerResolution.md` gains a "Controls mapper remapping"
section describing the eager remaps in this layer. It lists the mappers
that aren't sealed and Label's two public appends, and has a "Behavior
changes" section with migration guidance.
#### Validation
Run with the .NET SDK `12.0.100-alpha.1.26523.103`:
| Command | Result |
| --- | --- |
| `dotnet build src/Core/src/Core.csproj -c Release -p:MauiPlatforms=
-m:1 -v:q` | Passed, 0 warnings, 0 errors |
| `LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 dotnet test
src/Core/tests/UnitTests/Core.UnitTests.csproj -c Release
-p:MauiPlatforms= -m:1 -v:q` | Passed: 1,233 |
| `LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -c
Release -p:MauiPlatforms= -m:1 -v:q` | Passed: 7,467, skipped 30 |
| From `artifacts/bin/Core.UnitTests/Release/net12.0`:
`DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet exec --roll-forward Major
--runtimeconfig Microsoft.Maui.UnitTests.runtimeconfig.json --depsfile
Microsoft.Maui.UnitTests.deps.json
~/.nuget/packages/xunit.runner.console/2.9.3/tools/netcoreapp2.0/xunit.console.dll
Microsoft.Maui.UnitTests.dll -nocolor` | Total 1,233, Failed 0 |
| `dotnet build src/Controls/src/Core/Controls.Core.csproj -f
net12.0-android37.0 -c Release --disable-build-servers -nodeReuse:false`
| Passed. The only warning is the environment's Gradle SDK XML version
warning. |
| Same for `-f net12.0-ios27.1` and `-f net12.0-maccatalyst27.0` |
Passed, 0 warnings |
| `dotnet format Microsoft.Maui.sln --no-restore --exclude Templates/src
--exclude-diagnostics CA1822 --include <changed .cs files>
--verify-no-changes` | Exit 2, only from errors that already occur on
the base: RS0016 / RS0036 PublicAPI false positives in the format
workspace, and 4-space indentation in `SearchBarHandler2.Android.cs`.
Running it on the base for the same files gives the same errors. `dotnet
format whitespace --folder` passes for every other changed file. |
| `git diff --check` | Clean |
Not run: Windows build, device tests, CI.
### Issues Fixed
Part of #29952.
---------
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…40728)
<!-- copilot-assessment:v1 -->
### Agent assessment
Self-reported assessment, not an independent review.
Assessed revision: `837a686cae779f71c330b133bcfa58aa05f4b04c`
| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8.5/10 | ↑ Rebased on layer 2 `df9d3fbaca`. Core
1,235 tests pass under `dotnet test` and xunit.console. Controls 7,476
pass, 30 skipped.<br>↑ A non-`ElementHandler` Toolbar handler regression
test fails without the latest fix and passes with it.<br>↑
Mapper-related Controls test classes also pass when each runs
alone.<br>↑ Device tests on the iOS 27 simulator and an Android emulator
pass for the `Label`, `TabbedPage` and `RadioButton` categories.<br>↑
The new factory tests fail when `??=` is changed to `=`.<br>↑
Controls.Core compiles for Android, iOS and MacCatalyst with 0
warnings.<br>↑ Two code reviews found an order-dependent test and a
test-restore problem, both fixed. They found no product issues.<br>↓
Windows was not compiled locally, and no UI tests were run.<br>↓ CI has
not run on this head. |
<!-- /copilot-assessment -->
<!-- Please let the below note in for people that find this PR -->
> [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!
<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->
### Target Branch
| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |
- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).
For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.
### Description of Change
This is **layer 3 of 5** in a stack that splits #29952 ("[trimming]
Trimmable element handlers") into reviewable pieces. It is stacked on
#40725 (base branch
`simonrozsival-handlers-stack-l2-mapper-infrastructure`, currently
`df9d3fbaca`). The stack ultimately targets `main` (.NET 12).
1. #40721: context-aware handler activation and a Hot Reload `FullName`
fix.
2. #40725: mapper infrastructure that preserves customizations. Controls
remaps still run eagerly there.
3. **This PR: lazy Controls mapper remapping.** The DI default handler
table is unchanged.
4. #29952 itself, rebuilt on this layer: `[ElementHandler]` attributes,
removal of the eager DI default table, resolution precedence and caches.
5. The Copilot guidance PR #40715.
Controls used to apply all of its mapper remaps at startup: `UseMauiApp`
called every control's static `RemapForControls()`, and `Element`,
`VisualElement`, `Label` and `Switch` also remapped from static
constructors. This layer applies each remap the first time an instance
of that type is attached to a handler. #29952 needs this so a control's
remap code doesn't root that control's handler when the app never uses
it. Layer 2's customization records make the change safe: on sealed
mappers, app customizations compose with the Controls remaps whichever
runs first.
#### Mechanism
- New Core internals:
- `IControlsMapperRemappable`, with a single `RemapForControls()`
method.
- `OneTimeInitializationAction`, a blocking execute-once action backed
by `Lazy<bool>`. Concurrent callers wait until the action completes.
Tests are added for both behaviors.
- `ElementHandler.SetVirtualView()` calls `RemapForControls()` when the
virtual view implements `IControlsMapperRemappable`. The call runs after
`VirtualView` is set and before the platform view is created and
properties are mapped.
- The Controls `Element` implements the interface. The `Element.Handler`
setter calls the hook before `SetVirtualView`, so compatibility
renderers that don't derive from `ElementHandler` are covered too.
- Each Controls `*.Mapper.cs` now overrides `internal void
RemapForControls()`. The override calls `base.RemapForControls()` and
then runs a static `RemapForControlsOnce()` through its own
`OneTimeInitializationAction`. Attaching a `Label`, for example, runs
the `Element`, `VisualElement` and `Label` remaps in that order.
Unrelated control types don't share a global lock.
- `Toolbar` is not an `Element`, so it implements
`IControlsMapperRemappable` itself. Its `Handler` setter calls the hook
too, so custom toolbar handlers that don't derive from `ElementHandler`
are covered.
- `RemappingHelper.cs` and the empty `Layout.Mapper.cs` are deleted.
- The `Switch` static constructor, which only remapped, is removed.
`Label`'s static constructor now registers only its two public
`AppendToMapping` calls, Android `IsTextSelectable` and Apple
`FlowDirection`, which main also recorded at `Label` type
initialization. Everything else in Label's remap runs lazily.
- `CheckBox` keeps its static constructor for
`CommandProperty.DependsOn(CommandParameterProperty)`. A test checks
that the command dependency is set before any handler is attached.
- The `TabbedPage` remap (`TabbedViewHandler.PlatformViewFactory`) and
the Android `RadioButton` remap
(`RadioButtonHandler.PlatformViewFactory`) install their factory through
`InstallPlatformViewFactory()`, which uses `??=`. A factory the app
installed before the first attach is kept. New device tests cover both
an unset factory and an app factory installed first.
#### Hosting
`AppHostBuilderExtensions.SetupDefaults` no longer calls the eager
`RemapForControls` builder extension, which is removed. It still
registers the default handlers through `AddControlsHandlers()`, and it
still calls `Animations.ControlsNavigationTransitionHooks.Install()`.
That call used to run from inside the removed extension.
`ControlsDeviceTestExtensions` no longer calls the removed extension.
#### Behavior changes
Lazy remapping is the intended .NET 12 behavior that makes trimming
possible, so there is no runtime switch that restores startup remapping.
`docs/design/HandlerResolution.md` lists these changes with migration
guidance, next to layer 2's.
- **Remaps run when the first control of each type is attached, not
during `UseMauiApp`.** On sealed mappers, app customizations compose
with the Controls remaps no matter when they are registered, as
described in layer 2.
- **Copying mapper keys at startup misses the Controls keys.** Before
the first instance of a type is attached, the global mappers don't
contain the keys its remap adds, for example the `BackgroundColor`
redirect. Mappings already read through `GetProperty`, `GetCommand` or
the indexers still observe later remaps. Migration:
- Chain the custom mapper to the built-in one, for example `new
PropertyMapper<ILabel, ILabelHandler>(LabelHandler.Mapper) { ... }`.
- Or customize the built-in mapper with `AppendToMapping`,
`PrependToMapping`, `ModifyMapping` or `ReplaceMapping`.
- If a copy is unavoidable, take it after a control of that type has
been attached, for example from `HandlerChanged`.
- **Framework remaps of inherited keys build on the parent's mapping as
of the first attachment.** A remap now also includes app customizations
of the parent's key that were registered after `UseMauiApp` but before
that attachment. Migration: register customizations that should apply
everywhere before the first control is attached, for example in
`MauiProgram`, or customize the child mapper's key.
- **Platform view factories.** An app factory installed before the first
`TabbedPage` or Android `RadioButton` is attached is kept and replaces
the Controls factory. Reading the property during startup to wrap the
Controls factory now returns `null`.
- **Unchanged from main:** `Label`'s two public appends are still
recorded at `Label` type initialization.
#### Deviations from the #29952 head (`5db8263312`)
- `VisualElement.Mapper.cs` keeps the iOS/MacCatalyst
`UpdateCollectionViewAccessibilityTraits` code from main. The #29952
head deleted it by accident.
- Three `VisualElementMapperTests` tests read global mapper keys without
attaching a handler. They passed only when an earlier test in the same
process had attached one. They now call `new
VisualElement().RemapForControls()` first. The affected tests are
`BackgroundKeyIsMappedBeforeControlsBackgroundColorAndImageSourceKeys`,
`SemanticsKeyIsMappedBeforeControlsSemanticPropertiesKeys` and
`RealDerivedHandlerMappers_MapCanonicalKeysBeforeTheControlsRedirectKeys`.
The #29952 head has the same order dependency.
- The `Switch.Mapper.cs` comment now says "before the first Switch is
attached to a handler" instead of "is created".
- `Label.Mapper.cs` registers the two public appends from a static
constructor (`#if ANDROID || IOS || MACCATALYST`) instead of inside the
lazy remap. This addresses review feedback on #29952 and on this PR.
- `TabbedPage.Mapper.cs` and `RadioButton.Mapper.cs` move the `??=`
install into `InstallPlatformViewFactory()`. New device tests:
`TabbedPagePlatformViewFactoryTests.cs` and
`RadioButtonTests.Android.cs`.
- Left for layer 4: the `TrySetValue` moves out of `Element.cs`, the
`IElementHandler.cs` newline fix, `[ElementHandler]` attributes, the
`AddMauiControlsHandlers` no-op and the related device-test edits, and
the Windows `PreventGestureBubbling` refactor.
#### Docs
The "Controls mapper remapping" section of
`docs/design/HandlerResolution.md` keeps layer 2's mapper semantics and
now describes lazy remapping. It covers:
- the two attach hooks;
- the per-type one-time actions and their base-first order;
- command dependency setup and the platform view factory behavior;
- Label's appends, recorded at type initialization.
The section's "Behavior changes" list adds the lazy-remapping entries
above to layer 2's entries.
#### Validation
Run with the .NET SDK `12.0.100-alpha.1.26523.103`:
| Command | Result |
| --- | --- |
| `dotnet build Microsoft.Maui.BuildTasks.slnf` | Passed |
| `dotnet build src/Core/src/Core.csproj --disable-build-servers
-nodeReuse:false` (all local TFMs) | Passed, 0 warnings, 0 errors |
| `LANG=en_US.UTF-8 dotnet test
src/Core/tests/UnitTests/Core.UnitTests.csproj` | Passed: 1,235 |
| `LANG=en_US.UTF-8 dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj` |
Passed: 7,476, skipped 30 |
| From `artifacts/bin/Core.UnitTests/Debug/net12.0`:
`DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet exec --roll-forward Major
--runtimeconfig Microsoft.Maui.UnitTests.runtimeconfig.json --depsfile
Microsoft.Maui.UnitTests.deps.json
~/.nuget/packages/xunit.runner.console/2.9.3/tools/netcoreapp2.0/xunit.console.dll
Microsoft.Maui.UnitTests.dll -nocolor` | Total 1,230, Failed 0 (run on
the previous layer 2 base) |
| `dotnet test … Controls.Core.UnitTests.csproj --no-build --filter
"FullyQualifiedName~.<Class>"`, run once per class, for 12
mapper-related classes (`VisualElementMapperTests`,
`ControlsMapperTests`, `ElementTests`, `VisualElementTests`,
`ToolbarTests`, `LabelTests`, `RadioButtonTests`, `TabbedPageTests`,
`HostBuilderHandlerTests`, `StoryboardTests`,
`SemanticPropertyUnitTests`, `WindowsTests`) | All passed |
| `dotnet build src/Controls/src/Core/Controls.Core.csproj -f
net12.0-ios27.1 --disable-build-servers -nodeReuse:false` | Passed, 0
warnings |
| Same for `-f net12.0-maccatalyst27.0` and `-f net12.0-android37.0` |
Passed, 0 warnings |
| `pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1
-Project Controls -Platform ios -TestFilter "Category=Label"
-SkipXcodeVersionCheck` (iOS 27 simulator) | 99 passed, 5 skipped |
| Same with `-Platform android -DeviceUdid emulator-5556` | 113 passed,
1 skipped |
| `… -Platform ios -TestFilter "Category=TabbedPage"` | 90 passed, 3
skipped. Run before the restack; the new factory class passed again
after it (2/2). |
| `… -Platform android -TestFilter "Category=TabbedPage"` | 73 passed.
Run before the restack; the new factory class passed again after it
(2/2). |
| `… -Platform android -TestFilter "Category=RadioButton"` | 4 passed |
| The new factory tests with `??=` temporarily changed to `=` (iOS
TabbedPage, Android RadioButton) | The app-factory test fails, as
expected |
| `dotnet format whitespace --folder --verify-no-changes --include
<changed .cs files>` | Passed |
| `git diff --check` | Clean |
Not run: Windows build, UI tests, CI.
### Issues Fixed
Part of #29952.
---------
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
<!-- copilot-assessment:v1 -->
### Agent assessment
Self-reported assessment, not an independent review.
Assessed revision: `cdeafb72937dc746d00866464afe6553904c7d9f`
| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 7/10 | ↑ Two review rounds addressed:
most-specific interface resolution, plus Hot Reload replacement of
attribute and default handlers (scoped per app, reinstalled after
removal). Each fix has tests that fail without it.<br>↑ Rebased onto the
reviewed lower layers. Core 1,279 tests pass under dotnet test and
xunit.console, and Controls 7,532 pass. Controls compiles for Android,
iOS and MacCatalyst.<br>↑ The new Android compatibility-renderer default
activation device test passes 3/3 on an emulator.<br>↓ CI and the full
device suites on this head are not yet assessed.<br>↓ Windows paths are
compile-only; no Windows device coverage is added. |
<!-- /copilot-assessment -->
<!-- Please let the below note in for people that find this PR -->
> [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!
<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->
### Target Branch
| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |
- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).
For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.
### Description of Change
<!-- Enter description of the fix in this section -->
Follow-up to #28357 targeting **main / .NET 12**. Rebased onto the
trimmable-styles merge (#33561),
`04d36966ed9d334c056872d83741e973d61f6c55`.
#### Stack
This PR is **layer 4 of 5** in a stack split from the original single PR
for easier review. It is based on #40728, and its own diff covers only
the attribute-based resolution:
1. #40721: context-aware handler activation and Hot Reload type
matching.
2. #40725: mapper infrastructure that preserves app customizations, the
`*ForControls` remap helpers and sealed framework mappings.
3. #40728: lazy Controls mapper remapping on first handler attachment.
4. **This PR**: `[ElementHandler]` attributes on Controls types, removal
of the eager default DI registrations, resolution precedence and caches,
Hot Reload cache invalidation, Material3 and Apple Shell attribute
selection, Windows `PreventGestureBubbling` overrides and the
constructor-argument diagnostic.
5. #40715: Copilot guidance for working with handlers and mappers.
The sections below describe the combined feature; the activation, mapper
and lazy-remap sections are reviewed in layers 1–3. The combined tree is
unchanged from the reviewed `5db8263312bf8ea352e8f5a40b04e148c235f4cc`
except for the follow-up below.
Built-in Controls primarily declare `[ElementHandler]` instead of being
rooted by an eager default DI registration table. Controls-specific
mapper changes run lazily when handlers attach, while preserving
recorded application customizations. Open review items are listed below;
this description is not a merge-readiness approval.
#### Attribute-based handler resolution
`ElementHandlerAttribute` remains internal. The concrete handler type is
statically referenced for trimming/AOT. Although the attribute has
`Inherited = false`, the factory explicitly walks the base-type
hierarchy for fallback. Nested control-specific attributes preserve
conditional Android Material3 selection and Windows CollectionView
handler selection without unconditionally referencing both alternatives
on the active path.
`GetHandler(Type)` and `GetHandlerType(Type)` share the resolution
order:
1. Exact DI registration.
2. Attribute declared directly on the requested type.
3. The more specific of the nearest registered base class and the
nearest inherited attribute. An inherited attribute ranks like the
built-in registration its declaring class used to have; a registration
on that class or a subclass wins.
4. The most specific registered interface. With Controls defaults on,
the `IContentButton`/`IContentView` defaults compete here as interface
registrations.
5. Content interface fallbacks: `IContentButton` →
`ContentButtonHandler`, then `IContentView` → `ContentViewHandler`.
A conditional attribute can declare no handler, for example Apple
`ShellItem` when `UseiOSShellHandler` is off; resolution then continues
as if it were absent. An exact `AddHandler` still overrides defaults. A
registration for `Button` applies to an unannotated `FancyButton :
Button`, but registering `IButton` or `View` does not divert it from
`ButtonHandler`. Factory registrations remain authoritative even when
`GetHandlerType` cannot report an `ImplementationType` and therefore
returns `null`.
Controls enables an `ElementHandlerDefaultsEnabled` policy per app's
handler collection: `TryAddHandler` does not replace a directly declared
default or the `IContentButton`/`IContentView` defaults, but still
registers custom derived types that only inherit an attribute fallback.
Apps without Controls defaults retain normal `TryAddHandler` behavior;
`AddHandler` always remains an override. `UseMauiApp` enables the policy
before registration callbacks execute regardless of builder-chain order.
`AddMauiControlsHandlers` remains a non-obsolete compatibility no-op
returning the original collection, without enabling defaults or eagerly
remapping controls.
#### Cache ownership and invalidation
Only attribute and assignable-registration lookups are cached. The
complete resolution result and constructor-activation strategy are
**not** cached; current registrations and delegates are consulted on
every request, and transient requests create fresh handlers.
Each factory owns its resolution caches and builds its assignable index
from current descriptors, including raw DI registrations. Built-in
collection mutations (`Add`, `Insert`, indexer replacement, `Remove`,
`RemoveAt`, `Clear`) advance a version. Hot Reload metadata updates,
cache clearing, replaced-view callbacks and reset advance a checked
generation before views are recreated. Hot Reload registration
replacement also changes the collection version. A new cache generation
replaces the old dictionaries, preventing concurrent old-generation
readers from repopulating new state. Custom collections without mutation
tracking do not retain resolution caches.
Descriptor lookup stays consistent with indexer/list changes; removing
the last registration restores the preceding descriptor for that service
type. Cache lookup supports concurrent readers, but collection mutation
retains the standard `IServiceCollection` contract and must not run
concurrently with resolution.
#### Context-aware activation without an activation cache
`ElementExtensions.ToHandler` delegates reflection-based construction to
the factory. A public parameterless constructor is preferred when
present; otherwise `ActivatorUtilities.CreateInstance` resolves
dependencies from the current context (including its Android context).
Value-type handlers keep default construction. The constructor-presence
check avoids using `MissingMethodException` as ordinary control flow,
including first activation, without additional cache
ownership/invalidation complexity.
Direct public `GetHandler` callers retain parameterless-constructor
behavior. Custom factories retain their existing exception-based
injection fallback. Dependency failures propagate without retrying the
entire injection. Factory activation still uses the current service
provider/`IMauiContext`, and activated factory types participate in Hot
Reload replacement.
Historical matched **.NET 11** managed Release microbenchmarks measured
warm injected activation at roughly 9 µs with exception-first
construction versus 0.10–0.16 µs when missing-constructor exceptions
were avoided. Constructor checks were comparable to a factory-owned
activation cache; shared-host noise prevents claiming a small difference
between those alternatives. These are **not .NET 12 measurements,
Android startup claims, or APK-size results**.
#### Lazy mapper remapping and main integration
Controls `Element.SetHandler` invokes the remap hook before attaching
any handler, including compatibility renderers.
`ElementHandler.SetVirtualView` also invokes it for direct attachment
outside Controls. Each remappable type calls its base hook and owns a
blocking one-time initialization action; unrelated controls do not share
a global initialization lock.
Built-in mapper declarations seal their initial framework mappings.
Controls property/command remaps update those mappings underneath
recorded app customizations, preserving direct indexer overrides and
`AppendToMapping`, `PrependToMapping`, `ModifyMapping`, and
`ReplaceMapping` in registration order, including keys that are absent
until a lazy remap and keys inherited from chained mappers. See
`docs/design/HandlerResolution.md` for the ordering rules.
Command-property dependency setup remains in control initialization,
independent of handler attachment.
The main rebase preserves newer upstream functionality:
- `ContentButton` has its own handler attribute, `IContentButton`
fallback, sealed mapper and lazy Android ripple remapping.
- Switch OnColor remapping uses the lazy hook and
customization-preserving prepend behavior on Apple platforms.
- Android toolbar drawer-toggle remapping and the current
Android/Windows common-mapping scope are retained.
- RoundRectangle retains `IShapeWithStroke`; Shell retains the
reentrant-navigation unsubscribe fix; handler instrumentation is
preserved.
- Android ListView/TableView/Frame compatibility attributes retain
context-accepting activation through the factory's current-context
injection path.
- HybridWebView remains a deferred factory registration. Cell attributes
retain their platform scopes, and Windows CollectionView feature-switch
selection remains conditional.
- Controls navigation-transition hooks are installed independently of
the removed eager remapping helper.
Obsolete eager registration/remapping helpers and
Android-context-specific handler interfaces/attributes are removed.
Detailed resolution and activation contracts are documented in
`docs/design/HandlerResolution.md`.
#### Updated Android APK measurements (.NET 12)
**Trimmable styles + handlers reduce the plain template's signed
NativeAOT APK by 756 KiB (4.64%) compared with neither optimization.**
Since styles are already merged into main, this PR's incremental saving
over styles alone is **712 KiB**. The 4.64% figure is the combined
effect, not a handlers-only measurement.
| Framework state | NativeAOT APK (bytes) | Release/CoreCLR APK (bytes)
|
| --- | ---: | ---: |
| Neither styles nor handlers | 16,686,161 | 18,591,480 |
| Trimmable styles only | 16,641,105 | 18,591,480 |
| Trimmable styles + handlers | 15,912,017 | 18,398,968 |
Styles alone save 44 KiB with NativeAOT. Ordinary Release/CoreCLR saves
**188 KiB (1.04%)** with handlers; styles alone do not change that APK's
size under its default settings.
Measured the same unmodified `dotnet new maui -n Template --framework
net12.0` source, **without `--sample-content`**, as signed ARM64 APKs.
Framework revisions were `f38825f543a18fdcf5ac672b73835e50edd159f6`
(neither), `04d36966ed9d334c056872d83741e973d61f6c55` (styles), and
`9d2e9cf9b649b647777ec885cd31d1e303e3d49e` (both).
The matched local builds use SDK `12.0.100-alpha.1.26523.103`, Android
workload `37.99.0-preview.1.358`, and the same MAUI package version
`12.0.0-pr29952.local`, with separate feeds/caches. Non-MAUI
dependencies, runtime native libraries, signing key, app source and
relevant build settings were matched and package hashes checked.
NativeAOT uses full trimming and default trimmable styles; ordinary
Release uses CoreCLR, partial trimming and default composite R2R. Both
retain the SDK's default trimmable typemap and shipped/default profile
policy: **no app-trained or custom MIBC**.
These are APK file-size measurements, **not startup/JIT/runtime
measurements**. No handlers-only arm was measured; the incremental
handler saving includes its interaction with merged styles.
Local artifact build commands (all **passed**): `bash
artifacts/apk-styles-handlers-20261126/build-app.sh baseline aot`, `bash
artifacts/apk-styles-handlers-20261126/build-app.sh none aot`, `bash
artifacts/apk-styles-handlers-20261126/build-app.sh both aot`, and the
same three commands with `release` instead of `aot`. The historical
directory name `none` contains the styles-only revision; provenance is
checked against `source.sha`, not inferred from directory labels.
`python3 artifacts/apk-styles-handlers-20261126/measure.py` —
**passed**; verifies all six APKs and records exact
source/settings/package/profile identities in `results.json` alongside
retained commands, logs and binlogs. These scripts and outputs are local
investigation artifacts, not files added by this PR.
#### Local validation after the styles rebase (9d2e9cf)
The latest English-locale `net12.0` runs passed:
- `LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 dotnet test
src/Core/tests/UnitTests/Core.UnitTests.csproj -c Release
-p:MauiPlatforms= -m:1 -v:q` — **1,198 passed**.
- `LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -c
Release -p:MauiPlatforms= -m:1 -v:q` — **7,522 passed, 30 skipped**.
- `LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj -c
Release -p:MauiPlatforms= -m:1 -v:q` — **910 passed, 71 skipped**.
The previously reported comma-decimal failures were independently
reproduced on clean main and pass with the English locale; they are not
this PR's regressions. Existing coverage includes collection
mutation/raw registrations, custom unversioned collections, metadata and
handler replacement, context/app isolation, dependency errors without
retry, constructor preference/value types, first-use exception
elimination, recorded mapper customization and ContentButton
activation/type lookup.
Local Android framework packaging and the six trimmed/NativeAOT template
builds above passed. This does **not** establish device/UI behavior or
iOS/MacCatalyst/Windows validation for this head; CI attribution and
remaining review findings are still being assessed.
#### Review follow-up in 714715d
- **Handler precedence:** An inherited attribute ranks like the built-in
registration its declaring class used to have. The most specific
concrete candidate wins, and registered concrete types outrank
interfaces. With Controls defaults on, `IContentButton`/`IContentView`
defaults compete as interface registrations, and `TryAddHandler` no
longer replaces them.
- **Mapper customizations:** Lazy Controls remaps now compose underneath
app customizations, as if they had run at startup. This covers post-seal
assignments to absent keys, child customizations of parent keys that
only appear in a later lazy remap, and delegates read before a remap.
App-created mapper chains keep capture-at-customization semantics, and
wrapping a mapping read from a mapper no longer recurses.
- **Apple Shell:** `UseiOSShellHandler` again selects `ShellHandler` or
`ShellRenderer`, along with the item, section and content handlers.
Conditional attributes may declare no handler, so inactive handlers
remain trimmable.
- **CI fixes:** Hot Reload handler replacement matches by type name;
xunit.console loads the test assembly twice. The Material3 Picker
expectation is corrected, there is a blocking
`OneTimeInitializationAction` test, and the constructor-argument
diagnostic is clearer.
Validation: Core unit tests passed 1,223/1,223 under `dotnet test` and
xunit.console with `DOTNET_MODIFIABLE_ASSEMBLIES=debug`. Controls unit
tests passed 7,530, with 30 skipped. `Controls.Core` compiles for
`net12.0-ios27.1` and `net12.0-maccatalyst27.0`. The new Shell
resolution device tests passed 2/2 on MacCatalyst via
`.github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project
Controls -Platform maccatalyst -TestFilter "Category=Shell"
-IncludeClasses
"Microsoft.Maui.DeviceTests.ShellHandlerResolutionTests"`. Android and
iOS device runs and CI are not yet assessed on this head, and the APK
measurements above predate it.
Follow-up in 5db8263: lazy RadioButton (Android) and TabbedPage remaps
keep a `PlatformViewFactory` the app sets during startup. Resolution
fetches its cache once per request, and the typed `*ForControls` mapper
helpers check view and handler types before casting.
Follow-up when splitting the stack:
- Restores the iOS/MacCatalyst `UpdateCollectionViewAccessibilityTraits`
refresh on semantics changes. A rebase in 7fba985 had accidentally
dropped it.
- `VisualElementMapperTests` trigger the lazy remap before reading
global mapper keys. They previously passed only when another test had
attached a handler first.
- `HandlerResolution.md` gains the lower layers' more precise activation
and remapping text.
Validation on `c1de79de46`:
- Core unit tests: 1,225 passed under `dotnet test` and xunit.console.
- Controls unit tests: 7,530 passed, 30 skipped.
- The three mapper key-order tests pass when run on their own.
- `Controls.Core` compiles for `net12.0-android37.0`, `net12.0-ios27.1`
and `net12.0-maccatalyst27.0`.
Review follow-up (rebased; now in cdeafb7):
- **Interface resolution:** resolution now picks the most specific
matching interface before reporting an ambiguity. A concrete
`IContentButton` with `IButton` and `IContentView` registered resolves
to `ContentButtonHandler`, or to a registered `IContentButton` handler.
Unrelated registrations remain ambiguous.
- **Hot Reload:** pending handler replacements also apply to handlers
resolved from `[ElementHandler]` or the content interface defaults.
These have no collection descriptor, so the replacement is registered
for the requested view type the next time it is resolved.
- **Lower layers:** this PR was rebased onto #40728. That carries the
lower layers' review fixes: injected handlers are never retained as
singletons, the mapper fixes, and Label's public appends are back at
type initialization. HandlerResolution.md now has a combined "Behavior
changes" section with migration guidance.
Second review round:
- **Hot Reload:** replacements of attribute and default handlers apply
only to the collection passed to `RegisterHandlers`. A newly registered
collection receives replacements that were already applied to the
previous one, and a replacement whose registration was removed is
installed again.
- **Registration order:** HandlerResolution.md documents the changes.
`AddHandler` before `UseMauiApp()` now wins, `AddMauiControlsHandlers()`
no longer restores a replaced handler, and `RemoveAll` followed by
`TryAddHandler` no longer replaces an attributed default (use
`AddHandler`).
- **Android device test:** `CompatibilityRendererDefaultActivationTests`
covers default activation of the `ListView`, `TableView` and `Frame`
renderers with the current Android `Context`.
Validation on `cdeafb7293`:
- Core unit tests: 1,279 passed under `dotnet test` and xunit.console.
- Controls unit tests: 7,532 passed, 30 skipped.
- `Controls.Core` compiles for Android, iOS and MacCatalyst.
- The Android device test above passed 3/3.
Earlier validation on `a0f29fdbde`:
- Core unit tests: 1,271 passed under `dotnet test` and xunit.console.
- Controls unit tests: 7,531 passed, 30 skipped.
- `Controls.Core` compiles for `net12.0-android37.0`, `net12.0-ios27.1`
and `net12.0-maccatalyst27.0`.
#### Behavior changes
- **`AddMauiControlsHandlers()`:** Remains a compatibility no-op.
Calling it after registering a custom handler, for example
`AddHandler(typeof(Button), typeof(CustomButtonHandler))`, no longer
restores `ButtonHandler`. Remove the custom registration instead.
- **Custom `IMauiHandlersFactory` implementations:** Not supported.
Built-in defaults are resolved from attributes by the built-in factory,
not exposed as descriptors in `IMauiHandlersCollection`, so a
replacement factory can no longer resolve Controls views. A follow-up
will discourage and eventually remove this extension point.
`IMauiContext.Handlers` exposes the interface, so this needs a
replacement design rather than just `[Obsolete]`.
- **Lazy remaps:** Controls mapper remaps run on each control type's
first attachment instead of at `UseMauiApp`. App customizations made
during startup are preserved as described above. Label keeps its pre-PR
timing: its remaps already ran lazily from its static constructor.
Windows CollectionView, ListView and TableView device coverage is left
to the Windows controls maintainers.
### Issues Fixed
<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->
Supports the trimmable handler work started in #28357.
<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->
---------
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…ps (#40715)
<!-- copilot-assessment:v1 -->
### Agent assessment
Self-reported assessment, not an independent review.
Assessed revision: `9fc89e163e09ad84e46d29176e995dc810548920`
| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8.5/10 | ↑ Every rule was rechecked against the
final restacked #29952 head (`cdeafb7`): the source,
`docs/design/HandlerResolution.md` including its new Behavior changes
section, and the resolved review threads.<br>↑ The committed Pester
suite `Review-Expert.Tests.ps1` passes 13/13 locally with Pester 5.9.0.
It checks the pinned hash, the 32 headings, mapper routing to dimension
3 with negative cases, and C# routing to dimensions 12 and 18. Its
positive cases fail when the mapper rules are removed.<br>↓ The routing
change has not been exercised in a live `/review` run, and I have not
inspected the PowerShell Script Tests CI result for this head.<br>↓ No
automated validation exists for instruction or agent files. The
skill-validation workflow covers only `.github/skills/**`, which this PR
does not change.<br>↓ The guidance follows the stack's design, so it
must be revisited if a lower layer changes before merge. |
<!-- /copilot-assessment -->
<!-- Please let the below note in for people that find this PR -->
> [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!
<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->
### Target Branch
| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |
- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).
For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.
### Description of Change
This is the top layer of the trimmable-handlers stack:
1. #40721: context-aware handler activation
2. #40725: customization-preserving mapper infrastructure
3. #40728: lazy Controls mapper remaps
4. #29952: trimmable `[ElementHandler]` resolution
5. **This PR**: agent guidance
The base is the #29952 branch,
`dev/simonrozsival/net10.0-use-element-handler-attributes`. Merge this
PR after #29952 and the layers below it. It changes only agent guidance,
expert-review routing and its tests, not product code.
It records the stack's handler and mapper practices so future agents
follow them:
- **New `.github/instructions/handler-registration.instructions.md`**,
path-scoped to Controls `*.Mapper.cs` partials, Core/Controls hosting,
`Handlers/Element`, `PropertyMapper*`/`CommandMapper*`,
`ElementExtensions`, Hot Reload, handler-resolution and mapper tests,
and `HandlerResolution.md`. It covers:
- **Built-in defaults:** built-in controls declare their default handler
with the internal `[ElementHandler]` attribute on the control class
(platform-scoped), not with DI. `AddMauiControlsHandlers()` is a no-op.
DI is for app/library overrides and interfaces. HybridWebView's existing
`SetupDefaults` factory is an exception to keep, not a pattern to copy:
a factory delegate only defers construction, so the handler stays
rooted.
- **Construction:** attribute-resolved handlers need a public
parameterless constructor. Only `ToHandler()` injects constructor
arguments; a handler that needs them should be registered with an
`AddHandler` factory. The factory's provider resolves the current
`IMauiContext` only on context-taking paths such as `ToHandler()`, not
on public `GetHandler(Type)`. There is no activation cache, and custom
`IMauiHandlersFactory` implementations are unsupported.
- **Feature switches:** handler selection that depends on a feature
switch uses a nested `ElementHandlerAttribute` subclass that checks a
`[FeatureSwitchDefinition]` switch (Material3, Windows CollectionView,
Apple Shell). `GetHandlerType()` may return `null`.
- **Resolution:**
- It covers precedence, `GetHandler`/`GetHandlerType` consistency,
interface ambiguity, Hot Reload replacement of attribute handlers,
non-singleton injected handlers and `TryAddHandler` semantics.
- To replace a built-in handler, use `AddHandler`; it wins regardless of
registration order.
- Mapper customization is documented as startup-only.
- It links to `HandlerResolution.md` rather than duplicating it, and
asks for observable changes to be recorded in that doc's Behavior
changes section.
- **Lazy remaps:** remaps run on first attach, base type first.
`Toolbar`, which is not an element, triggers its remap from its own
handler setter.
- Remaps use the `*ForControls` helpers, not the public customization
APIs. Label's Android `IsTextSelectable` and Apple `FlowDirection`
public appends are the documented exception; they run from `static
Label()`, not the remap.
- Static factories are installed through `InstallPlatformViewFactory()`
with `??=`, and `DependsOn` stays in type initialization.
- Remapped mappers call `.WithFrameworkMappingsSealed()`.
`SwitchHandler.Mapper` and `TextButtonMapper`/`ImageButtonMapper` remain
unsealed exceptions.
- A framework remap of an inherited key builds on the parent's mapping
as it is at first attachment.
- For inherited keys, sealed mappers return child-bound mappings and
unsealed ones return the chained mapping. Internals use
`PropertyMapper.GetPropertyDirect`.
- **Testing:**
- Platform attribute branches need device tests. Tests that toggle a
switch use `DisableParallelization` and restore it.
- Mapper-preservation tests cover customizations both before and after
the remap.
- Tests that read global mappers must trigger the lazy remap first (`new
VisualElement().RemapForControls()`).
- Tests must not assume `Type` identity across assembly loads.
- **`handler-patterns.instructions.md`**: adds bullets on sealing (with
the unsealed exceptions) and the remap helpers, plus a short
"Registering Built-in Handlers" section that links to the new file.
- **`maui-expert-reviewer.md`**: replaces the outdated "use
`ModifyMapping` for Controls-layer overrides" check.
- Dimension 3 gets checks for remaps, sealing, unsealed exceptions,
child-key remaps, `??=`, `DependsOn` and test-order independence.
- Dimension 12 gets checks for resolution consistency, unsupported
custom factories and the `AddMauiControlsHandlers()` no-op.
- Dimension 18 gets checks for attributes, feature-switch selection and
device coverage. The existing HybridWebView factory is exempt from the
built-in-handler check.
- Dimensions 12 and 18 activate for every `.cs` file, both in the
rulebook's Conditional Dimensions table and in `Review-Expert.ps1`.
Self-reviews that pick dimensions from the rulebook, such as try-fix
Step 6, therefore also reach the `[ElementHandler]` checks.
- **Dimension Routing** now routes Controls `*.Mapper.cs` partials, Core
mapper infrastructure (`PropertyMapper*`, `CommandMapper*`,
`MappingCustomizationSequence.cs`) and `*Mapper*Tests.cs` to dimension
3, so mapper-only changes get the remap and test-order checks.
- **`.github/scripts/Review-Expert.ps1`**: mirrors those three routing
rules in `Get-ExpertExpectedDimensions` and updates the pinned routing
SHA-256. This changes only routing data; it adds no tokens, checkouts or
PR-code execution.
- **New `.github/scripts/Review-Expert.Tests.ps1`**: Pester regression
tests for the routing, run by the existing `powershell-script-tests.yml`
gate. That workflow now also triggers on
`.github/agents/maui-expert-reviewer.md`, so a rulebook routing edit
without a matching hash update fails CI.
- **`copilot-instructions.md`**: adds a short "Handlers and Mappers"
pointer, because a focused `applyTo` cannot match control class files
(`Label.cs`, `Button.cs`, ...).
- **`README-AI.md`**: indexes the handler instruction files.
No skills changed: `code-review` delegates handler checks to
`maui-expert-reviewer`, and no other skill describes handler
registration.
**Validation:** No automated tests exist for instruction or agent
markdown, and `skill-validation.yml` runs only for `.github/skills/**`.
- `pwsh -c 'Import-Module Pester -RequiredVersion 5.9.0; Invoke-Pester
.github/scripts/Review-Expert.Tests.ps1'`: **passed**, 13/13.
- With the three mapper routing rules temporarily removed from
`Review-Expert.ps1`, the same run failed 6 of 13 tests, so the suite
catches the original gap.
`git diff --check` is clean.
### Issues Fixed
Follow-up to #29952; no separate issue.
<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->
---------
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Agent assessment
Self-reported assessment, not an independent review.
Assessed revision:
eb23e06bfaa9b22e0f21d17133e2a3a7972f0b77dotnet testand xunit.console. Controls 7,467 pass, 30 skipped.↑ 5 of the new or affected tests fail with main's activation code. The Hot Reload test fails under xunit.console without the
FullNamefix.↑ The review-reported singleton regression is fixed; its test fails without the fix. Mutation checks confirm the custom-factory fallback and no-retry tests.
↑ An Android device test of per-context
Contextand dependency capture passes 2/2 on an API 35 emulator and fails if the application context is substituted.↑ Controls.Core compiles for Android, iOS and MacCatalyst. An independent code review found no issues.
↓ Controls.Core platform compiles ran on an earlier head; later commits change only a lifetime check and tests.
↓ iOS, Mac Catalyst and Windows device tests were not run.
↓ CI has not run on this head.
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!
Target Branch
mainnet11, for reviewFor .NET 11 fixes, only a maintainer retargets the approved PR to the active
inflight lane and merges it after CI validates that final base. Do not merge
individual fixes directly into
net11; agents must not retarget or merge.Description of Change
This is layer 1 of 5 in a stack that splits #29952 ("[trimming] Trimmable element handlers") into reviewable pieces. It is based on
mainat04d36966ed9d334c056872d83741e973d61f6c55.PropertyMapper/CommandMapper, sequenced customizations, the*ForControlshelpers andWithFrameworkMappingsSealed. Controls remaps switch to the helpers but still run eagerly atUseMauiApp.OneTimeInitializationAction,IControlsMapperRemappable, per-typeRemapForControlsand the attach hooks. The DI default table is still present.[ElementHandler]attributes, removal of the eager DI default table, resolution precedence and versioned caches.Activation
ElementExtensions.ToHandlerno longer catchesMissingMethodException, and no longer records the view type in a process-widehandlersWithConstructorsset. It calls the internalMauiHandlersFactory.GetHandlerWithInjectioninstead.MauiFactory.CreateInstancebecomes aprotected virtualactivation hook.MauiHandlersFactoryoverrides it for type-based handler registrations reached throughToHandler():ActivatorUtilities.CreateInstanceresolves constructor arguments from the currentIMauiContextservices, including the AndroidContext. No missing-constructor exception is thrown first.main.IMauiContextand run on every request.GetHandler(Type)callers keep the parameterless-constructor-only behavior.IMauiHandlersFactoryimplementations keep the exception-based fallback. It applies toMissingMethodExceptionand to aHandlerNotFoundExceptionthat wraps one._serviceCache,RegisteredHandlerServiceTypeSet, and the internalElementHandlerAttribute<THandler>path.AddControlsHandlersregistrations are untouched, including the Android ListView, TableView and Frame context factory lambdas.Hot Reload
MauiHotReloadHelper.RegisterHandlerReplacementnow matches registered handler types byFullName. It no longer resolves the name throughAppDomainassemblies, which returns a differentTypewhen an assembly is loaded twice. xunit.console, the runner used in CI, loads the test assembly twice.GetServicepath, so their types are now recorded and Hot Reload replacement applies to them.Tests and docs
HostBuilderHandlerTestsgain activation tests covering:HandlerNotFoundExceptionwrapping aMissingMethodException;MissingMethodException;HandlerNotFoundExceptionwrapping aMissingMethodException(injects) or an unrelated exception (propagates withoutGetHandlerType).src/Core/tests/DeviceTests/HandlerActivationTests.Android.cs) activates an injected handler throughToHandlerwith twoMauiContexts wrapping distinct Android contexts, for transient and singleton registrations, and asserts each handler captures its ownContextand dependency.ElementHandlerAttribute, and C# 11 generic attributes are not available in the test project.docs/design/HandlerResolution.mdgains a "Handler Instantiation" section and an updatedMauiFactorybullet. Both describe only this layer's behavior.Deferred to layer 4: the attribute-specific constructor diagnostic ("handlers declared with
ElementHandlerAttributemust have a public parameterless constructor…"). Onmain, the attribute requiresTHandler : new(), so that error cannot occur here.Validation (run locally)
dotnet build src/Core/src/Core.csproj -c Release -p:MauiPlatforms= -m:1 -v:q— passed, 0 warnings, 0 errors.LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 dotnet test src/Core/tests/UnitTests/Core.UnitTests.csproj -c Release -p:MauiPlatforms= -m:1 -v:q— passed, 1,157 tests.DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet exec --roll-forward Major --runtimeconfig Microsoft.Maui.UnitTests.runtimeconfig.json --depsfile Microsoft.Maui.UnitTests.deps.json ~/.nuget/packages/xunit.runner.console/2.9.3/tools/netcoreapp2.0/xunit.console.dll Microsoft.Maui.UnitTests.dll -nocolor, run fromartifacts/bin/Core.UnitTests/Release/net12.0— passed, 1,157 tests, 0 failed.LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -c Release -p:MauiPlatforms= -m:1 -v:q— passed, 7,467 tests, 30 skipped.pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Core -Platform android -DeviceUdid emulator-5556 -TestFilter "Category=MauiContext" -IncludeClasses "Microsoft.Maui.DeviceTests.HandlerActivationTests"on an API 35 emulator — passed, 2/2.f1b80314ab; later commits only add a lifetime check inMauiHandlersFactory.csand tests.dotnet build src/Controls/src/Core/Controls.Core.csproj -f <tfm> -c Release --disable-build-servers -nodeReuse:false -v:q, run after buildingMicrosoft.Maui.BuildTasks.slnf— passed, 0 errors:net12.0-android37.0: the first build reported 1 warning, not captured. A rebuild after touchingMauiHandlersFactory.csreported none.net12.0-ios27.1andnet12.0-maccatalyst27.0: 0 warnings.dotnet format Microsoft.Maui.sln --no-restore --exclude Templates/src --exclude-diagnostics CA1822 --include <changed .cs files> --verify-no-changes— passed.git diff --check— passed.src/Core/srcrestored, 5HostBuilderHandlerTestsfail:ConstructorInjectionDoesNotAffectOtherApps,ConstructorInjectionFailureIsNotRetried,ConstructorInjectionUsesCurrentContextAndHonorsFactoryOverrides,ToHandlerPrefersParameterlessConstructorWhenInjectionIsAlsoAvailable, and the existingHandlerCollectionFactoriesReceiveTheCurrentMauiContext. The last one is polluted by main's process-wide set.HotReloadHelperchange reverted,HotReloadReplacesHandlerAfterConstructorInjectionfails under xunit.console.SingletonRegistrationRequiringInjectionCreatesHandlerPerActivationfails. Removing the wrapped-exception fallback failsCustomHandlersFactoryWrappedMissingConstructorFallsBackToInjection; broadening it to any inner exception failsCustomHandlersFactoryWrappedUnrelatedExceptionPropagates. DroppingConstructorInjectionAttemptedfrom that catch failsWrappedMissingConstructorFromInjectedDependencyIsNotRetried.mauiContext.Context.ApplicationContextinstead of the current Android context fails both device-test cases.Not run: iOS, Mac Catalyst and Windows device tests, and Windows builds.
Issues Fixed
Part of #29952; supports the trimmable handler work started in #28357.