Skip to content

fix(http): keep EndpointOptions bindable in trimmed apps that use AddRefitClient or AddKiotaClient - #3267

Open
kazo0 wants to merge 2 commits into
mainfrom
dev/sb/http-endpoint-trimming
Open

kazo0 wants to merge 2 commits into
mainfrom
dev/sb/http-endpoint-trimming

Conversation

@kazo0

@kazo0 kazo0 commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

GitHub Issue (If applicable): closes #3266

PR Type

  • Bugfix
  • Build or CI related changes

What is the current behavior?

In a trimmed Release build (iOS and Android use TrimMode=partial, WebAssembly full), AddRefitClient and AddKiotaClient lose the Url from their endpoint section. Refit throws BaseAddress must be set on the HttpClient instance; Kiota's BaseUrl is null.

AddClientWithEndpoint binds the section with ConfigurationBinder.Get<TEndpoint> and annotates TEndpoint with [DynamicallyAccessedMembers], but AddRefitClientWithEndpoint and AddKiotaClientWithEndpoint pass an unannotated TEndpoint through. The trimmer cannot carry the requirement to EndpointOptions, so it removes the Url and UseNativeHandler setters from Uno.Extensions.Http (trimmable since it became IsAotCompatible), and the section binds to an empty object. Details and a standalone repro are in #3266.

What is the new behavior?

  • TEndpoint is annotated [DynamicallyAccessedMembers(PublicParameterlessConstructor | PublicProperties)] on AddRefitClientWithEndpoint and AddKiotaClientWithEndpoint, and TInterface [DynamicallyAccessedMembers(PublicConstructors)] on AddRefitClient and AddRefitClientWithEndpoint.
  • The two AddClientWithEndpoint overloads in Uno.Extensions.Http are narrowed from All to the same PublicParameterlessConstructor | PublicProperties. That is everything the configuration binder touches. It creates the instance through the public parameterless constructor and binds properties with public getters and setters, walking up the BaseType chain. It touches no fields, methods, events or nested types. All also kept nested types, so an endpoint type that declared a delegate dragged in IL2026/IL2111 warnings on Delegate(Object,String) (reproduced; gone with the narrowed flags). Relaxing a generic parameter's requirement is not breaking for callers.
  • Annotations only; no API or behaviour change for untrimmed apps.
  • New src/Uno.Extensions.Http.TrimmingTests: a console app (not a VSTest assembly, since trimming only happens on publish) that registers a Refit and a Kiota client from an endpoint section and checks each gets the configured base address. It also registers AddRefitClientWithEndpoint with a derived DerivedEndpointOptions and checks that both the inherited Url and a property declared on the derived type are bound. The test app itself is IsTrimmable, so that derived type is only kept by the annotation. A recording primary handler answers locally, so nothing goes to the network.
  • stage-build-packages.yml publishes it trimmed after the unit tests and runs it; a non-zero exit code fails the job.

Verified locally (macOS osx-arm64 for the first two rows, then on Windows win-x64 after narrowing):

Refit Kiota
Trimming test, this PR's library code PASS PASS
Trimming test, main's library code FAIL: BaseAddress must be set on the HttpClient instance FAIL: BaseUrl null
Narrowed annotations (win-x64) Result
Full trimming test 4/4 PASS
Refit TEndpoint annotation removed derived property FAIL (null), IL2091 back
Only the derived registration (nothing else keeps EndpointOptions) inherited Url PASS

Before the narrowing (with All), against packages packed from this branch, a separate trimmed repro app passed with only Refit or only Kiota registered, so each annotation fixes its own client; the trimmed Uno.Extensions.Http.dll kept both setters. The two IL2091 warnings on AddRefitClientWithEndpoint are gone with the narrowed flags too (and come back when the Refit annotation is removed).

PR Checklist

Other information

Not in this PR, as follow-ups:

  • AddRefitClient and AddRefitClientWithEndpoint call AddClientWithEndpoint, which is [RequiresUnreferencedCode]/[RequiresDynamicCode], without carrying those attributes themselves (IL2026 inside the assembly), so apps get no warning at their call site, unlike AddKiotaClient. Adding them, and IsAotCompatible on Uno.Extensions.Http.Refit, is correct but adds warnings in consuming apps.
  • The new CI step ran locally on macOS and Windows; the first run on the windows-2022 agent is this PR's CI.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Sn8GmJ41W3eBgT7866J3jV

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
LastRequestUri = request.RequestUri;
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("ok") });

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

False positive: the response is the handler's return value; HttpClient owns and disposes it.

Comment on lines +41 to +44
catch (Exception ex)
{
Fail("AddRefitClient", $"{ex.GetType().Name}: {ex.Message}");
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a specific catch for the expected InvalidOperationException (Refit's "BaseAddress must be set on the HttpClient instance"). The generic fallback stays, so any other exception is reported as a FAIL instead of crashing the run before the remaining checks.

@kazo0
kazo0 marked this pull request as ready for review October 27, 2026 19:09
@kazo0
kazo0 added this pull request to stack #3270 October 27, 2026 20:23

@jonpryor jonpryor left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please avoid .All.

Additionally, what I'd like to know, and what the PR description doesn't provide, is how Kiota & Refit "find" the UseNativeHandler and Url properties. Is it "only" via Reflection, or is there some other mechanism? Do they require properties for Reflection lookup, or Fields as well? Methods? Other?

public static IServiceCollection AddKiotaClientWithEndpoint<
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
TClient,
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use of .All is very problematic; see also: unoplatform/uno@d9dcb1c

The "short and weird" version is that use of .All caused IL2026 warnings around the System.Delegate constructor, Delegate.CreateDelegate, etc.:

	ILC : Trim analysis warning IL2026: Uno.Material.WinUI.GlobalStaticResources.ResourceDictionarySingleton__mergedpages_v1_c15678b9f7eb6ae0d4e176be633434fa.Get_9(Object): Using member 'System.Delegate.Delegate(Object,String)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. The target method might be removed.
	ILC : Trim analysis warning IL2111: Uno.Material.WinUI.GlobalStaticResources.ResourceDictionarySingleton__mergedpages_v1_c15678b9f7eb6ae0d4e176be633434fa.Get_9(Object): Method 'System.Delegate.Delegate(Type,String)' with parameters or return value with `DynamicallyAccessedMembersAttribute` is accessed via reflection. Trimmer can't guarantee availability of the requirements of the method.

It was very weird, and encountering that scenario only requires that TEndpoint contain a delegate type:

class MyEndpoint
{
    public delegate void Whatever();
}
// …
ServiceCollectionExtensions.AddKiotaClientWithEndpoint<…, MyEndpoint>(…);

DynamicallyAccessedMemberTypes.All should be avoided if at all possible.

Is there something "less than" .All that can be used? .PublicProperties perhaps?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Narrowed to PublicParameterlessConstructor | PublicProperties on all four TEndpoints, including both AddClientWithEndpoint overloads in Uno.Extensions.Http. Those had to change too, or the Refit call site would raise IL2091.

On how Url/UseNativeHandler are found: Refit and Kiota never see EndpointOptions. AddClientWithEndpoint binds it with Uno.Extensions.Configuration.Internal.ConfigurationBinder.Get<TEndpoint>, which works only through reflection:

  • GetConstructors checks for a public parameterless constructor, then Activator.CreateInstance creates the object.
  • GetProperties(Public|NonPublic|Instance|Static|DeclaredOnly) runs on each type up the BaseType chain. Non-public properties are listed but skipped, because BindNonPublicProperties is never set. Values are written with PropertyInfo.SetValue through public getters and setters.
  • GetInterfaces() runs only to detect collections and dictionaries, which an options type isn't.

No fields, methods, events or nested types are touched. AddClientWithEndpoint then sets HttpClient.BaseAddress from options.Url, and Refit and Kiota read the base address from that HttpClient.

I reproduced your case: with a nested delegate in the endpoint type, All produced IL2026 on Delegate(Object,String) and IL2111. The narrowed flags don't. The trimming test now also covers a derived endpoint type (DerivedEndpointOptions), which fails without the annotation.

public static IServiceCollection AddRefitClientWithEndpoint<
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
TInterface,
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See prior comment about the perils of .All. Please find something narrower.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, narrowed the same way here; see the reply above.

kazo0 and others added 2 commits October 28, 2026 12:05
…RefitClient or AddKiotaClient

AddClientWithEndpoint binds the endpoint section with ConfigurationBinder.Get<TEndpoint>
and annotates TEndpoint with DynamicallyAccessedMembers(All), but AddRefitClientWithEndpoint
and AddKiotaClientWithEndpoint passed their own unannotated TEndpoint through, so the
trimmer could not carry the requirement to EndpointOptions (IL2091, folded into IL2104 for
Refit and suppressed by RequiresUnreferencedCode for Kiota). With TrimMode=partial, the
iOS Release default, Uno.Extensions.Http is trimmed, the Url and UseNativeHandler setters
are removed, the section binds to an empty object, and the client has no BaseAddress:
Refit throws 'BaseAddress must be set on the HttpClient instance', Kiota's BaseUrl is null.

Annotate TEndpoint on both wrappers, and TInterface on the Refit ones (PublicConstructors,
as AddClientWithEndpoint requires). Verified with a trimmed osx-arm64 console app: 8.0.0-dev.135
reproduces both failures; with this change both setters survive and both clients get their
base address, each annotation fixing its own client independently.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Sn8GmJ41W3eBgT7866J3jV
Uno.Extensions.Http.TrimmingTests is a console app, not a VSTest assembly: trimming only
happens on publish, so CI publishes it trimmed (TrimMode=partial, the iOS and Android
Release mode) after the unit tests and runs it. It registers a Refit and a Kiota client
from an endpoint configuration section and checks that each gets the configured base
address, with a recording primary handler so no request leaves the process.

Without the EndpointOptions annotations both checks fail (Refit: 'BaseAddress must be set
on the HttpClient instance'; Kiota: BaseUrl null) and the app exits 1; with them both pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Sn8GmJ41W3eBgT7866J3jV
@kazo0
kazo0 force-pushed the dev/sb/http-endpoint-trimming branch from 5580a56 to 3dc7f2e Compare October 28, 2026 17:17
Comment on lines +72 to +75
catch (Exception ex)
{
Fail("AddKiotaClient", $"{ex.GetType().Name}: {ex.Message}");
}
public static IServiceCollection AddKiotaClientWithEndpoint<
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
TClient,
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)]

@jonpryor jonpryor Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to move the expression DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicPropert into a named const? See e.g.

internal const DynamicallyAccessedMemberTypes ViewModelRequirements =
DynamicallyAccessedMemberTypes.PublicConstructors
| DynamicallyAccessedMemberTypes.PublicProperties
;

I don't know offhand if this assembly references Uno.Extensions.Core and has access to its internals, but if it does, you could update Annotations with:

partial static class Annotations
{
    internal const DynamicallyAccessedMemberTypes EndpointRequirements =
		  DynamicallyAccessedMemberTypes.PublicParameterlessConstructor
		| DynamicallyAccessedMemberTypes.PublicProperties
		;
}

Then ServiceCollectionExtensions could use [DynamicallyAccessedMembers(Annotations.EndpointRequirements)].

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is already addressed in the current branch: the TEndpoint generic parameters in the Add*WithEndpoint overloads include DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties), so the trim-safe binding for endpoint options is in place.

@mergify

mergify Bot commented Nov 12, 2026

Copy link
Copy Markdown

Tick the box to add this pull request to the merge queue (same as @mergifyio queue). If it does not match the queue conditions yet, it enters the queue once it does.

  • Queue this pull request

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Http] AddRefitClient and AddKiotaClient lose the endpoint Url in trimmed builds ("BaseAddress must be set on the HttpClient instance")

3 participants