NativeLibraryLoader for Assembly with ModuleInitializer

December 18, 2020c#c#9

In C# 9 the ModuleInitializer atrribute was introduced which makes it easy to implement loading of native assemblies in your library.

internal static class NativeLibraryLoader
{
    [ModuleInitializer]
    public static void Initialize()
    {
        NativeLibrary.SetDllImportResolver(typeof(NativeLibraryLoader).Assembly, ResolveDllImport);
    }

    private static IntPtr ResolveDllImport(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
    {
        // Implement all your assembly loading logic here.
        
        if (libraryName == GL.LibraryName)
        {
            return NativeLibrary.Load("opengl32");
        }

        return IntPtr.Zero;
    }
}