我正在开发 PowerShell 二进制模块。它使用 Json.NET和其他图书馆。
我收到此异常“无法加载文件或程序集‘Newtonsoft.Json,Version=6.0.0.0,Culture=neutral,PublicKeyToken=30ad4fe6b2a6aeed’或其依赖项之一。系统找不到指定的文件。”
在硬盘上我有它的更新版本(版本 7.0.2)
像这样的问题在控制台、网络或桌面应用程序中很容易解决,使用 app.config 或“web.config”通过这样的行
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
</dependentAssembly>
如何为 PowerShell 二进制模块做类似的事情?
最佳答案
在开发使用多个第 3 方库(Google API、Dropbox、Graph 等)的 PowerShell 模块时,我自己遇到了这个问题后,我发现以下解决方案是最简单的:
public static Assembly CurrentDomain_BindingRedirect(object sender, ResolveEventArgs args)
{
var name = new AssemblyName(args.Name);
switch (name.Name)
{
case "Microsoft.Graph.Core":
return typeof(Microsoft.Graph.IBaseClient).Assembly;
case "Newtonsoft.Json":
return typeof(Newtonsoft.Json.JsonSerializer).Assembly;
case "System.Net.Http.Primitives":
return Assembly.LoadFrom("System.Net.Http.Primitives.dll");
default:
return null;
}
}
请注意,在该方法中,我有两种可能的方法来引用程序集,但它们都做同样的事情,它们强制使用该程序集的当前版本。 (不管是通过类引用加载还是dll文件加载)
要在任何 cmd-let 中使用它,请在 PSCmdLet 的 BeginProcessing() 方法中添加以下事件处理程序。
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_BindingRedirect;
关于c# - PowerShell 二进制模块程序集依赖性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32398597/