Dynamically Resolve P/Invoke Native Module Loading in .NET

In .NET, the default location where P/Invoke native modules (.dll, .so or .dylib) are searched for is the same directory as the calling managed assembly.

There are cases, however, when one would like to change the source location of the loaded assembly dynamically. Such needs may arise while making test harnesses, resolving compatibility issues and similar. In .NET, there are several extension points for that, but what I found to be working is the following:

using System.Runtime.InteropServices;

//...

NativeLibrary.SetDllImportResolver(alternetUIAssembly,
	(libraryName, assembly, searchPath) =>
	{
		if (libraryName == "MyLibrary")
		{
			var nativeDllFilePath = Path.Combine("My/Desired/Path", @"MyLibrary.dll");
			if (File.Exists(nativeDllFilePath))
				return NativeLibrary.Load(nativeDllFilePath);
		}

		return IntPtr.Zero;
	});