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

.NET6下WPF Caliburn.Micro无法加载其他项目ViewModel实例问题

解决方案

1. 替换动态加载程序集的方式

不要通过遍历目录加载CommonView.dll,直接通过项目引用的类型获取程序集,避免.NET6发布/路径问题:

protected override IEnumerable<Assembly> SelectAssemblies()
{
    return new List<Assembly>
    {
        Assembly.GetExecutingAssembly(),
        typeof(AboutViewModel).Assembly // 直接从CommonView项目的ViewModel类型获取程序集
    };
}

2. 确保容器扫描所有相关程序集

如果使用Caliburn.Micro的SimpleContainer,在Configure方法中添加对CommonView程序集的扫描,让容器自动注册ViewModel:

private SimpleContainer _container;

protected override void Configure()
{
    _container = new SimpleContainer();
    
    _container.Scan(scan =>
    {
        scan.Assembly(Assembly.GetExecutingAssembly());
        scan.Assembly(typeof(AboutViewModel).Assembly); // 扫描CommonView程序集
        scan.WithDefaultConventions(); // 按约定注册ViewModel和View
    });

    // 注册框架服务
    _container.Instance(_container);
}

3. 检查视图的生成设置

确保CommonView项目中对应的View(如AboutView.xaml)的生成操作设置为Page,且命名严格遵循Caliburn约定:AboutViewModel对应AboutView。


问题原因

之前用Assembly.LoadFile加载程序集存在两个核心问题:

  • .NET6的发布模式(如单文件部署)下,Directory.GetCurrentDirectory()的路径可能不符合预期,导致无法找到目标DLL;
  • LoadFile加载的程序集会处于独立的加载上下文,Caliburn.Micro的视图定位器和容器扫描无法正确识别其中的类型,因此GetInstance返回null。

直接通过类型引用获取程序集的方式更稳定,也符合.NET6的项目依赖管理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 20:05:10