Skip to content

Instantly share code, notes, and snippets.

@axelheer
Last active April 10, 2024 10:48
Show Gist options
  • Save axelheer/bf7d7f94f59990191363ad2a9f3bf45e to your computer and use it in GitHub Desktop.
Save axelheer/bf7d7f94f59990191363ad2a9f3bf45e to your computer and use it in GitHub Desktop.
Custom *Assembly load context* as *Module assembly initializer* using *Assembly dependency resolver* to load all the things! Solves dependency conflicts of multiple PowerShell modules and honors .deps.json files...
using System;
using System.Linq;
using System.Management.Automation;
using System.Reflection;
using System.Runtime.Loader;
namespace MyModule
{
public class Resolver : AssemblyLoadContext, IModuleAssemblyInitializer, IModuleAssemblyCleanup
{
private static readonly AssemblyLoadContext LoadContext
= AssemblyLoadContext.GetLoadContext(typeof(AssemblyResolver).Assembly);
private static readonly AssemblyDependencyResolver ReferenceResolver
= new(typeof(AssemblyResolver).Assembly.Location);
public void OnImport()
{
LoadContext.Resolving += OnResolving;
LoadContext.ResolvingUnmanagedDll += OnResolvingUnmanagedDll;
}
private static Assembly OnResolving(AssemblyLoadContext loadContext, AssemblyName assemblyName)
=> ReferenceResolver.ResolveAssemblyToPath(assemblyName) is string assemblyPath
? loadContext.LoadFromAssemblyPath(assemblyPath)
: null;
private static IntPtr OnResolvingUnmanagedDll(Assembly assembly, string unmanagedDllName)
=> ReferenceResolver.ResolveUnmanagedDllToPath(unmanagedDllName) is string libraryPath
? NativeLibrary.Load(libraryPath)
: IntPtr.Zero;
public void OnRemove(PSModuleInfo psModuleInfo)
{
LoadContext.ResolvingUnmanagedDll -= OnResolvingUnmanagedDll;
LoadContext.Resolving -= OnResolving;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment