You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Uno Platform集成Autofac时ViewModelLocator在Android/WASM无法生效问题

问题根因

Uno Platform 针对非桌面端(Android/WASM/iOS等)的XAML资源加载采用了和UWP/WPF不同的延迟实例化策略:你当前把ViewModelLocator放在了MergedDictionaries嵌套的独立ResourceDictionary中,这类资源在没有被显式访问的前提下,启动阶段不会被主动实例化,因此构造函数不会触发,也不会抛出异常。此外Android/WASM平台的链接器裁剪逻辑也可能把未被显式引用的Locator相关代码直接裁剪掉,导致逻辑不执行。

可行解决方案

  • 移除冗余的嵌套ResourceDictionary
    把ViewModelLocator直接定义到根级ResourceDictionary下,不要嵌套额外的ResourceDictionary层,修改后的App.xaml资源部分如下:
    <Application
         <Application.Resources>
          <ResourceDictionary>
             <ResourceDictionary.MergedDictionaries>
                <XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls" />
             </ResourceDictionary.MergedDictionaries>
    
             <!--  MVM light view model locator  -->
             <local:ViewModelLocator x:Key="ViewModelLocator" d:IsDataSource="True" />
          </ResourceDictionary>
       </Application.Resources>
    </Application>
    
  • 显式触发ViewModelLocator初始化
    在共享项目的App.xaml.cs的OnLaunched生命周期方法中,主动获取一次该静态资源,强制触发构造函数执行,代码参考:
    protected override void OnLaunched(LaunchActivatedEventArgs args)
    {
        // 强制实例化ViewModelLocator,提前完成IOC配置
        _ = Resources["ViewModelLocator"] as ViewModelLocator;
        
        // 原有启动逻辑保持不变
        Window.Current.Activate();
    }
    
  • 规避链接器裁剪问题
    给ViewModelLocator类添加[Preserve]特性,防止发布阶段被链接器裁剪:
    [Preserve(AllMembers = true)]
    public class ViewModelLocator
    {
        // 原有逻辑保持不变
    }
    
  • 临时替换绑定写法验证
    如果上述配置完成后仍未生效,可以先把MainPage的XAML绑定改为后台代码赋值,先确认Locator实例化逻辑正常,再排查XAML绑定解析问题:
    public MainPage()
    {
        InitializeComponent();
        var locator = Application.Current.Resources["ViewModelLocator"] as ViewModelLocator;
        DataContext = locator[typeof(TestViewModel)];
    }
    

内容的提问来源于stack exchange,提问作者G.D.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 09:36:01