.NET MAUI Release构建失败:程序集加载异常与运行时崩溃
解决.NET MAUI Release构建及运行时问题
一、修复Mono AOT编译时无法加载System.Transactions.Local的错误
- 在项目文件(.csproj)的Release配置组中,添加对
System.Transactions.Local程序集的显式引用,确保AOT编译时能找到该程序集:<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Android'"> <!-- 保留原有配置 --> <ItemGroup> <PackageReference Include="System.Transactions.Local" Version="7.0.0" /> </ItemGroup> </PropertyGroup> - 若上述方法无效,可在AOT编译参数中强制包含该程序集,在Release配置中添加:
<MonoAotAdditionalArgs>--aot=full,nodebug,assembly=System.Transactions.Local.dll</MonoAotAdditionalArgs>
二、解决XAML解析错误(找不到ViewModel引用)
1. 确保ViewModel被正确注册且未被裁剪
- 在
MauiProgram.cs中确认PostsViewModel已注册到依赖注入容器:builder.Services.AddTransient<PostsViewModel>(); // 可根据业务需求替换为AddScoped/AddSingleton - 为
PostsViewModel类添加[Preserve]特性,防止Trimming(即使禁用也可能存在隐式裁剪)移除该类型:using Foundation; // 跨平台场景需引入此命名空间;Android平台也可使用Android.Runtime.Preserve [Preserve(AllMembers = true)] public class PostsViewModel : ObservableObject { // 类实现代码 }
2. 检查XAML绑定配置
- 确认
HomePage.xaml中ViewModel的引用路径正确,示例如下:<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:vm="clr-namespace:YourApp.ViewModels" x:DataType="vm:PostsViewModel" x:Class="YourApp.Views.HomePage"> <ContentPage.BindingContext> <vm:PostsViewModel /> </ContentPage.BindingContext> <!-- 页面内容 --> </ContentPage> - 若使用静态资源引用ViewModel,需确保资源声明正确且未被裁剪:
<ContentPage.Resources> <vm:PostsViewModel x:Key="ViewModel" /> </ContentPage.Resources> <!-- 绑定需使用正确的资源键 --> <Label Text="{Binding Title}" BindingContext="{StaticResource ViewModel}" />
3. 彻底禁用Trimming(临时排查用)
在项目文件的Release配置中明确禁用Trimming相关选项:
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Android'"> <EnableTrimAnalyzer>false</EnableTrimAnalyzer> <TrimMode>None</TrimMode> <PublishTrimmed>false</PublishTrimmed> </PropertyGroup>
三、额外排查建议
- 查看Sentry日志的完整调用栈,确认是否有其他被裁剪的依赖类型,针对性添加
[Preserve]特性或调整Trimming配置。 - 删除项目的
bin和obj文件夹清理构建缓存后,重新构建Release版本,避免缓存导致的异常。
内容的提问来源于stack exchange,提问作者ReticentRobot
相关产品推荐
相关产品推荐

