VSIX项目使用ASP.NET Core SignalR客户端遇程序集加载异常
解决VSIX项目中SignalR Hub连接的程序集加载异常问题
问题核心原因
你遇到的FileNotFoundException本质是VSIX的程序集加载上下文与ASP.NET Core SignalR Client 7.x的依赖模型不兼容:
- VSIX运行在Visual Studio(devenv.exe)进程中,使用传统.NET Framework的程序集加载机制;
- Microsoft.AspNetCore.SignalR.Client 7.x是为.NET 5+设计的,其依赖的
Microsoft.Extensions.*、System.Runtime等组件基于.NET Core的依赖模型,直接复制文件无法让Visual Studio进程正确加载这些组件。
解决方案
方案一:改用兼容.NET Framework的SignalR Client版本(最稳妥)
ASP.NET Core SignalR Client 2.x系列原生支持.NET Framework 4.6.1+,后续3.0+版本转向.NET Core优先,对.NET Framework的兼容仅通过.NET Standard实现,在VSIX场景下易出问题。
- 卸载当前的
Microsoft.AspNetCore.SignalR.Client 7.0.5,通过NuGet安装2.2.0版本; - 调整代码适配2.x API:
private void Execute(object sender, EventArgs e) { var url = "http://localhost:9200/myHub"; var connection = new HubConnectionBuilder() .WithUrl(url) .Build(); // 手动实现自动重连(2.x无内置WithAutomaticReconnect) connection.Closed += async (error) => { await Task.Delay(new Random().Next(0, 5) * 1000); await connection.StartAsync(); }; }
方案二:强制适配7.x版本(复杂,可能遇更多依赖问题)
如果必须使用7.x版本,通过程序集绑定重定向+强制复制依赖解决加载问题:
- 在项目的
app.config中添加程序集绑定重定向,将所有相关依赖版本统一到7.0.0.0:<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Microsoft.Extensions.Options" publicKeyToken="adb9793829ddae60" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" /> </dependentAssembly> <!-- 若后续出现其他依赖缺失,继续添加对应绑定重定向 --> </assemblyBinding> </runtime> - 确保所有依赖的
Copy Local属性为True:- 展开项目的References,找到所有
Microsoft.Extensions.*、System.Runtime、Microsoft.AspNetCore.SignalR.Client相关引用,右键→属性,设置Copy Local = True;
- 展开项目的References,找到所有
- 修改.csproj文件,强制复制所有NuGet依赖到输出目录:
<PropertyGroup> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> </PropertyGroup> - 在创建HubConnection前,手动将VSIX输出目录添加到程序集加载路径:
private void Execute(object sender, EventArgs e) { // 获取VSIX输出目录 var assemblyDir = Path.GetDirectoryName(typeof(MyCoolCommand).Assembly.Location); // 添加到程序集搜索路径 AppDomain.CurrentDomain.AppendPrivatePath(assemblyDir); var url = "http://localhost:9200/myHub"; var connection = new HubConnectionBuilder() .WithUrl(url) .WithAutomaticReconnect() .Build(); }
方案三:升级到.NET Core/.NET 6+的VSIX项目(长期最优)
创建VSIX Project (for .NET)(目标.NET 6或更高版本),该项目类型基于.NET Core的加载机制,完美兼容ASP.NET Core SignalR Client 7.x,不会出现依赖加载问题。
内容的提问来源于stack exchange,提问作者Чингиз Олжабаев
相关产品推荐
相关产品推荐

