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

Autofac DependencyResolutionException求助:激活AppViewModel时抛出异常

排查Autofac依赖注入激活异常问题

问题背景

原本正常运行的代码,无改动情况下出现Autofac依赖解析异常,激活Argos.AppViewModel时,在创建Argos.Networking.NetworkService实例环节抛出错误。

相关代码

App类初始化代码

public static IContainer Container;
public App()
{
    InitializeComponent();
    TheTheme.SetTheme();
    CultureInfo greekCulture = new CultureInfo("el-GR");
    CultureInfo.DefaultThreadCurrentCulture = greekCulture;
    Thread.CurrentThread.CurrentCulture = greekCulture;
    Thread.CurrentThread.CurrentUICulture = greekCulture;
    VersionTracking.Track();
    AppHelper.LoadCfgSettings();
    var e = DependencyService.Get<IEnvironment>();
    var tid = e.GetAndroidSerial();
    AppHelper.WriteSetting(AppHelper.TidKey, tid);
    //class used for registration
    var builder = new ContainerBuilder();
    //scan and register all classes in the assembly
    var dataAccess = Assembly.GetExecutingAssembly();
    builder.RegisterAssemblyTypes(dataAccess)
        .AsImplementedInterfaces().AsSelf();
    Container = builder.Build();
    BindingContext = Container.Resolve<AppViewModel>();
    MainPage = new AppShell();
}

AppViewModel构造函数

public AppViewModel(IMessageServices messageServices ,IDialogMessage dialogMessage, INetworkService networkService, INavigationService navigationService, IAppDownloader appDownloader)
{
    _messageServices = messageServices;
    _messageServices.CreateHubConnection();
    _dialogMessage = dialogMessage;
    _navigationService = navigationService;
    _appDownloader = appDownloader;
    _networkService = networkService;
    _wakeUp = DependencyService.Get<IWakeUp>();
    _deviceManipulation = DependencyService.Get<IDeviceManipulation>();
    _messageServices.OnMessageReceived += _messageServices_OnMessageReceived;
    _messageServices.OnUrlLinkReceived += _messageServices_OnUrlLinkReceived;
    _messageServices.OnBlockReceived += _messageServices_OnBlockReceived;
    _messageServices.OnCommandReceived += _messageServices_OnCommandReceived;

    MessageList = new ObservableRangeCollection<MessageModel>();
}

错误信息

Autofac.Core.DependencyResolutionException: '激活Argos.AppViewModel -> Argos.Networking.NetworkService时抛出异常。'

排查建议

  • 查看InnerException详情:Autofac的外层异常通常会包含InnerException,里面会有具体的错误原因,比如某个依赖未注册、构造函数执行时抛出业务异常等,这是最关键的排查点。
  • 检查NetworkService构造函数:确认它的依赖项是否都被Autofac正确注册,或者构造函数内部是否有未处理的异常(比如初始化网络连接失败、读取配置文件出错)。
  • 验证Assembly注册范围:当前代码通过Assembly.GetExecutingAssembly()扫描注册程序集内的类型,确认NetworkService及其依赖是否在该程序集中,若不在则需补充注册对应程序集。
  • 排查环境/配置变化:即使代码未改动,也可能是配置文件修改、设备权限变更(比如NetworkService需要的网络权限被禁用)、NuGet依赖包自动更新导致兼容性问题。
  • 调试执行流程:在NetworkService构造函数和AppViewModel构造函数中添加断点,逐步执行定位具体出错步骤。

内容的提问来源于stack exchange,提问作者MarsMan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 22:53:08