PowerShell Binary Module assembly dependency error PowerShell Binary Module assembly dependency error json json

PowerShell Binary Module assembly dependency error


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;    }}

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)

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

AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_BindingRedirect;


The closest i've found so far is:

  1. Add the problem assembly to the manifest's RequiredAssemblies - this causes it to be loaded into the AppDomain when the module is loaded.
  2. Use the code from this SO answer - it adds an AssemblyResolve handler to the current AppDomain, which searches for assemblies already loaded and returns ones which match by strong name and PublicKeyToken
  3. After using the module, you have to do the following to avoid stack overflows when exiting: [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($OnAssemblyResolve)

Steps 1 and 2 could both be encapsulated in the module, but step 3 can't, which means this isn't suitable as a general solution - the caller has to know about it. So I'm still searching for a better way.


You need to add a manifest to your module.

The simplest way is:

New-ModuleManifest -RequiredAssemblies:"path\to\newtonSoft.dll"

Then modify the manifest file manually for any other tweaks.

If the manifest doesn't solve the problem, you may need to pull out the nuclear hammer and set the binding redirects for ALL of powershell as mentioned in Powershell - Assembly binding redirect NOT found in application configuration file