作为第三方程序插件运行时,WPF引用NuGet包报错问题求助
解决思路
针对作为Autodesk Inventor插件的WPF类库加载外部NuGet包(如MahApps)时出现的FileNotFound异常,可从以下几个方向排查:
修复程序集加载上下文差异
插件被Inventor进程加载时,默认程序集加载路径可能不包含插件输出目录,导致找不到依赖DLL。可通过注册AssemblyResolve事件手动指定加载路径:AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { var assemblyName = new AssemblyName(args.Name).Name; var pluginDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); var assemblyPath = Path.Combine(pluginDir, $"{assemblyName}.dll"); return System.IO.File.Exists(assemblyPath) ? System.Reflection.Assembly.LoadFrom(assemblyPath) : null; };建议在插件初始化的最开始注册该事件。
调整资源加载路径
WPF类库无App.xaml,在MainWindow中导入资源时,需确保Pack URI路径完整且正确。例如MahApps的资源引用应使用完整格式:<ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" /> <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" /> <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Themes/Light.Blue.xaml" /> </ResourceDictionary.MergedDictionaries>避免使用相对路径导致资源定位失败。
强制复制所有依赖程序集
检查NuGet包依赖的所有DLL的Copy Local属性是否设为True,或直接在项目文件中添加配置强制复制:<PropertyGroup> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> </PropertyGroup>确保嵌套依赖的DLL也被复制到插件输出目录。
确保在UI线程初始化窗口
Inventor的插件线程与UI线程分离,窗口创建和资源加载需在UI线程执行。使用Inventor的Invoke方法切换线程:InventorApplication.Invoke(delegate() { // 窗口创建、资源加载等代码移至此处 var mainWindow = AppHost.Services.GetRequiredService<MainWindow>(); // ...后续窗口初始化逻辑 });排查程序集版本冲突
用Process Explorer等工具查看Inventor进程已加载的程序集,确认是否存在与MahApps等包版本冲突的情况。若有冲突,可尝试调整NuGet包版本匹配Inventor环境,或在插件配置文件中添加程序集重定向规则:<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="MahApps.Metro" publicKeyToken="some-token" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-x.x.x.x" newVersion="x.x.x.x" /> </dependentAssembly> </assemblyBinding> </runtime>
内容的提问来源于stack exchange,提问作者Bas Nederveen
相关产品推荐
相关产品推荐

