Skip to content

Instantly share code, notes, and snippets.

@ap0llo
Last active February 3, 2018 16:54
Show Gist options
  • Save ap0llo/0755f792f87ca1db0f76 to your computer and use it in GitHub Desktop.
Save ap0llo/0755f792f87ca1db0f76 to your computer and use it in GitHub Desktop.
Loads the assembly System.Net.Http.Primitives from the same location as the executing assembly in a powershell module. This is necessary when using the Google .NET client library in powershell Cmdlets
using System;
using System.IO;
using System.Management.Automation;
using System.Reflection;
/// <summary>
/// Powershell module intializer that ensures that the assembly System.Net.Http.Primitives required by Goolge client library is loaded correctly
/// </summary>
public class ModuleAssemblyLoader : IModuleAssemblyInitializer
{
#region Constants
private const string s_SystemNetHttpPrimitives = "System.Net.Http.Primitives";
private const string s_Dll = ".dll";
#endregion
#region IModuleAssemblyInitializer Implementation
public void OnImport()
{
//register for the assembly resolve event
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += AssemblyResolveEventHandler;
}
#endregion
#region Private Methods
private static Assembly AssemblyResolveEventHandler(object sender, ResolveEventArgs args)
{
//parse the name of the requested assembly
var assemblyName = new AssemblyName(args.Name);
//for System.Net.Http.Primitives use the assembly located next to the cmdlet assembly
if (assemblyName.Name == s_SystemNetHttpPrimitives)
{
var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var assembly = Assembly.LoadFile(Path.Combine(dir, s_SystemNetHttpPrimitives + s_Dll));
return assembly;
}
//do not change behaviour for other assemblies
return null;
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment