.NET Framework 4.8项目执行Import-Module时加载Microsoft.Bcl.AsyncInterfaces失败
解决.NET Framework 4.8项目PowerShell导入模块时的Microsoft.Bcl.AsyncInterfaces加载失败问题
问题根源
根据Fusion++日志,PowerShell.exe加载模块时会使用自身的配置文件,而非项目的app.config,导致你在项目里配置的程序集绑定重定向规则完全不生效。Autofac v5.2.0.0尝试加载Microsoft.Bcl.AsyncInterfaces v1.0.0.0,但你的项目实际依赖的是v6.0.0.0,重定向规则没被应用,所以出现找不到文件的错误。
解决方案
方案1:修改PowerShell的系统配置文件(全局生效)
- 找到对应PowerShell版本的配置文件路径:
- 32位PowerShell:
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe.config - 64位PowerShell:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe.config
- 32位PowerShell:
- 右键以管理员身份编辑该文件,添加项目app.config里的绑定重定向规则,示例代码:
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Microsoft.Bcl.AsyncInterfaces" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
- 保存后重启PowerShell,再执行
Import-Module即可。注意这个修改会影响所有PowerShell会话。
方案2:自定义配置文件启动PowerShell(局部生效)
- 新建一个配置文件(比如命名为
MyModuleConfig.config),复制项目app.config里的<runtime>节点内容进去。 - 用指定配置文件启动PowerShell:
powershell.exe -config "C:\path\to\MyModuleConfig.config"
- 在这个PowerShell窗口里执行
Import-Module,此时绑定重定向规则会生效。
方案3:在模块代码中手动处理程序集加载(需修改模块源码)
- 在模块的初始化代码里添加
AssemblyResolve事件,手动指定加载正确版本的程序集:
using System; using System.Reflection; // 模块初始化时注册事件 AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { var requestedAssembly = new AssemblyName(args.Name); // 匹配目标程序集 if (requestedAssembly.Name.Equals("Microsoft.Bcl.AsyncInterfaces", StringComparison.OrdinalIgnoreCase) && requestedAssembly.Version <= new Version(6, 0, 0, 0)) { // 替换为你项目中该程序集的实际路径,比如从NuGet包目录加载 string assemblyPath = @"..\packages\Microsoft.Bcl.AsyncInterfaces.6.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll"; return Assembly.LoadFrom(assemblyPath); } return null; };
- 重新编译模块后再导入,就能自动加载正确版本的程序集。
方案4:预加载正确版本的程序集(PowerShell命令行解决)
- 在执行
Import-Module之前,先用Add-Type加载v6.0.0.0版本的程序集:
Add-Type -Path "C:\path\to\your-project\bin\Debug\Microsoft.Bcl.AsyncInterfaces.dll" Import-Module "C:\path\to\your-module.dll"
- 这样PowerShell会先加载正确版本,后续Autofac请求旧版本时会直接使用已加载的程序集。
内容的提问来源于stack exchange,提问作者criveracrum
相关产品推荐
相关产品推荐

