Skip to content

Commit d4829b8

Browse files
jfversluisCopilot
andauthored
Only enable Aspire functionality in non-optimized builds (i.e. Debug) (#31494)
* Only enable Aspire functionality in debug * Default to false and add warning * Update src/Controls/src/Build.Tasks/nuget/buildTransitive/netstandard2.0/Microsoft.Maui.Controls.targets Co-authored-by: Copilot <[email protected]> * Update src/Core/src/Hosting/Dispatching/AppHostBuilderExtensions.cs Co-authored-by: Copilot <[email protected]> * Update src/Core/src/Hosting/Dispatching/AppHostBuilderExtensions.cs * Add documentation and flip default value * Update Microsoft.Maui.Controls.targets * Use Optimized MS Build --------- Co-authored-by: Copilot <[email protected]>
1 parent 8541619 commit d4829b8

File tree

4 files changed

+77
-0
lines changed

4 files changed

+77
-0
lines changed

docs/design/FeatureSwitches.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ The following switches are toggled for applications running on Mono for `TrimMod
1616
| MauiNamescopesSupported | Microsoft.Maui.RuntimeFeature.AreNamescopesSupported | Enable support for Namescopes, FindByName if the application uses it, or to keep supporting runtime and XamlC XAML inflators |
1717
| EnableDiagnostics | Microsoft.Maui.RuntimeFeature.EnableDiagnostics | Enables diagnostic for the running app |
1818
| EnableMauiDiagnostics | Microsoft.Maui.RuntimeFeature.EnableMauiDiagnostics | Enables MAUI specific diagnostics, like VisualDiagnostics and BindingDiagnostics. Defaults to EnableDiagnostics |
19+
| _EnableMauiAspire | Microsoft.Maui.RuntimeFeature.EnableMauiAspire | When enabled, MAUI Aspire integration features are available. **Warning**: Using Aspire outside of Debug configuration may introduce performance and security risks in production. |
1920

2021
## MauiEnableIVisualAssemblyScanning
2122

@@ -99,3 +100,28 @@ Defaults to `false`
99100
Enable VisualDiagnostics and BindingDiagnostics
100101

101102
Defaults to `EnableDiagnostics`
103+
104+
## _EnableMauiAspire
105+
106+
Controls whether MAUI Aspire integration features are enabled at runtime.
107+
108+
**Default Value**: `true`
109+
110+
**Automatic Configuration**: This feature switch is automatically configured by the MAUI build system based on optimization settings:
111+
- **Non-optimized builds (Debug)**: Enabled (`true`)
112+
- **Optimized builds (Release)**: Disabled (`false`)
113+
- **Regular builds (no AOT/Trimming)**: Uses runtime default (`true`)
114+
115+
The automatic configuration only applies when `PublishAot=true` OR `TrimMode=full` is set.
116+
117+
**Manual Override** (Not Recommended): While it's possible to manually override this setting, it's not recommended as it may introduce performance and security risks in production:
118+
119+
```xml
120+
<PropertyGroup>
121+
<_EnableMauiAspire>true</_EnableMauiAspire>
122+
</PropertyGroup>
123+
```
124+
125+
**Warning**: Manually setting this property in optimized builds (where `Optimize=true`) will trigger build warning MA002.
126+
127+
**Trimming Behavior**: When `_EnableMauiAspire=false` and trimming is enabled, the .NET trimmer can eliminate MAUI Aspire-related code paths, reducing the final application size and potentially improving performance in production scenarios.

src/Controls/src/Build.Tasks/nuget/buildTransitive/netstandard2.0/Microsoft.Maui.Controls.targets

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,13 @@
272272
<PropertyGroup>
273273
<MauiEnableIVisualAssemblyScanning Condition="'$(MauiEnableIVisualAssemblyScanning)' == ''">false</MauiEnableIVisualAssemblyScanning>
274274
</PropertyGroup>
275+
276+
<!-- Validate _EnableMauiAspire usage - warn when user manually sets it in optimized builds where it conflicts with intended behavior -->
277+
<Warning
278+
Code="MA002"
279+
Text="The _EnableMauiAspire property should not be set manually. Using Aspire outside the Debug configuration may introduce performance and security risks in production. This property is automatically configured based on build configuration."
280+
Condition="'$(_EnableMauiAspire)' != '' and '$(Optimize)' == 'true' and '$(MauiDisableAspireValidation)' != 'True'"/>
281+
275282
<PropertyGroup Condition="'$(PublishAot)' == 'true' or '$(TrimMode)' == 'full'">
276283
<MauiShellSearchResultsRendererDisplayMemberNameSupported Condition="'$(MauiShellSearchResultsRendererDisplayMemberNameSupported)' == ''">false</MauiShellSearchResultsRendererDisplayMemberNameSupported>
277284
<MauiQueryPropertyAttributeSupport Condition="'$(MauiQueryPropertyAttributeSupport)' == ''">false</MauiQueryPropertyAttributeSupport>
@@ -280,6 +287,10 @@
280287
<MauiHybridWebViewSupported Condition="'$(MauiHybridWebViewSupported)' == ''">false</MauiHybridWebViewSupported>
281288
<!-- FIXME: https://github.com/xamarin/xamarin-macios/issues/22065 -->
282289
<MobileAggressiveAttributeTrimming Condition="'$(PublishAot)' == 'true' and '$(MobileAggressiveAttributeTrimming)' == ''">false</MobileAggressiveAttributeTrimming>
290+
291+
<!-- Set _EnableMauiAspire based on whether optimizations are enabled when not already set -->
292+
<_EnableMauiAspire Condition="'$(_EnableMauiAspire)' == '' and '$(Optimize)' != 'true'">true</_EnableMauiAspire>
293+
<_EnableMauiAspire Condition="'$(_EnableMauiAspire)' == ''">false</_EnableMauiAspire>
283294
</PropertyGroup>
284295
<ItemGroup>
285296
<RuntimeHostConfigurationOption Include="Microsoft.Maui.RuntimeFeature.IsIVisualAssemblyScanningEnabled"
@@ -318,6 +329,10 @@
318329
Condition="'$(EnableDiagnostics)' != ''"
319330
Value="$(EnableDiagnostics)"
320331
Trim="true" />
332+
<RuntimeHostConfigurationOption Include="Microsoft.Maui.RuntimeFeature.EnableMauiAspire"
333+
Condition="'$(_EnableMauiAspire)' != ''"
334+
Value="$(_EnableMauiAspire)"
335+
Trim="true" />
321336
</ItemGroup>
322337
</Target>
323338
</Project>

src/Core/src/Hosting/Dispatching/AppHostBuilderExtensions.cs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System;
22
using System.Collections;
33
using System.Collections.Generic;
4+
using System.Linq;
45
using System.Text.RegularExpressions;
56
using Microsoft.Extensions.Configuration;
67
using Microsoft.Extensions.DependencyInjection;
@@ -35,8 +36,34 @@ public static MauiAppBuilder ConfigureDispatching(this MauiAppBuilder builder)
3536

3637
public static MauiAppBuilder ConfigureEnvironmentVariables(this MauiAppBuilder builder)
3738
{
39+
if (!RuntimeFeature.EnableMauiAspire)
40+
{
41+
return builder;
42+
}
43+
3844
IDictionary environmentVariables = Environment.GetEnvironmentVariables();
3945

46+
#if ANDROID
47+
const string androidEnvVarFilePath = "/data/local/tmp/ide-launchenv.txt";
48+
49+
// For Android we read the environment variables from a text file that is written to the device/emulator
50+
// If the file not exists, we will use the default environment variables which is less stable
51+
if (OperatingSystem.IsAndroid() && System.IO.File.Exists(androidEnvVarFilePath))
52+
{
53+
var envVarLines = System.IO.File.ReadAllLines(androidEnvVarFilePath);
54+
55+
var fileEnvironmentVariables = envVarLines
56+
.Select(line => line.Split('=', 2))
57+
.ToDictionary(parts => parts[0], parts => parts[1]);
58+
59+
// Merge file environment variables into the existing environment variables
60+
foreach (var kvp in fileEnvironmentVariables)
61+
{
62+
environmentVariables[kvp.Key] = kvp.Value;
63+
}
64+
}
65+
#endif
66+
4067
string devTunnelId = environmentVariables["DEVTUNNEL_ID"]?.ToString() ?? string.Empty;
4168

4269
var variablesToInclude = new HashSet<string>

src/Core/src/RuntimeFeature.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ static class RuntimeFeature
2626
const bool SupportNamescopesByDefault = true;
2727
const bool EnableDiagnosticsByDefault = false;
2828
const bool IsMeterSupportedByDefault = true;
29+
const bool EnableAspireByDefault = true;
2930

3031
#pragma warning disable IL4000 // Return value does not match FeatureGuardAttribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute'.
3132
#if NET9_0_OR_GREATER
@@ -138,6 +139,14 @@ internal set
138139
AppContext.SetSwitch($"{FeatureSwitchPrefix}.{nameof(EnableMauiDiagnostics)}", value);
139140
}
140141
}
142+
143+
#if NET9_0_OR_GREATER
144+
[FeatureSwitchDefinition($"{FeatureSwitchPrefix}.{nameof(EnableMauiAspire)}")]
145+
#endif
146+
public static bool EnableMauiAspire => AppContext.TryGetSwitch($"{FeatureSwitchPrefix}.{nameof(EnableMauiAspire)}", out bool isEnabled)
147+
? isEnabled
148+
: EnableAspireByDefault;
149+
141150
#pragma warning restore IL4000
142151
}
143152
}

0 commit comments

Comments
 (0)