PowerShell Binary Module程序集相关性错误 [英] PowerShell Binary Module assembly dependency error

查看:95
本文介绍了PowerShell Binary Module程序集相关性错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发 PowerShell二进制模块.它使用 Json.NET 和其他库.

I am developing PowerShell binary module. It uses Json.NET and other libraries.

我收到此异常无法加载文件或程序集'Newtonsoft.Json,Version = 6.0.0.0,Culture = neutral,PublicKeyToken = 30ad4fe6b2a6aeed'或其依赖项之一.系统找不到指定的文件.'

I am getting this exception "Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.'

在硬盘驱动器上,我有它的更新版本(版本7.0.2)

On hard drive I have an updated version of it (version 7.0.2)

类似的问题可以在控制台,Web或桌面应用程序中轻松解决,只需通过 app.config 或"web.config"通过这样的行

Problems like that are easily solved in console, web or desktop application, with app.config or "web.config" via lines like this

<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二进制模块做类似的事情?

How can I do something similar for PowerShell binary module?

推荐答案

在自己开发使用多个第三方库(Google API,Dropbox,Graph等)的PowerShell模块时遇到此问题后,我发现以下解决方案是最简单的:

After coming across this issue myself while developing a PowerShell module that uses multiple 3rd party libraries (Google API, Dropbox, Graph, etc) I found the following solution was the simplest:

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文件加载)

Note in the method, I've got two possible ways to reference the assembly, but both of them do the same thing, they force the current version of that assembly to be used. (Regardless if it is loaded via class reference or dll file load)

要在任何cmd-let中使用此命令,请在PSCmdLet的BeginProcessing()方法中添加以下事件处理程序.

To use this in any cmd-let add the following event handler in the BeginProcessing() method of the PSCmdLet.

AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_BindingRedirect;

这篇关于PowerShell Binary Module程序集相关性错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆