Search code examples
c#json.netdependency-managementcom-interop

COM-Interop assembly not finding a native (.Net) dependancy when called from Vb


I have a C# COM-Interop assembly which I am calling from a Visual Basic 6 application. This assembly makes HTTP requests to send and retrieve JSON.

The assembly works fine when being testing with a C# test client.

However, when using it from with the VB6 app, the following error is returned:

"Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified."

The Newtonsoft.Json.dll is located within the same folder as the COM-Interop DLL (TLB).

Does the Newtonsoft.Json.dll need to be explicitly loaded? Or maybe placed in the GAC?


Solution

  • Hans provided a great explanation for why this happens. Let me offer a workaround for making this work without having to register the Json DLL in the GAC or copying it to the VB6 EXE directory.

    In your COM-visible C# library, we can tell the .NET runtime environment to search for the Json DLL in the directory of the C# library instead of the "usual" paths. We do that by attaching our own handler to the AssemblyResolve event:

    AppDomain.CurrentDomain.AssemblyResolve += (sender, e) =>
    {
        // We only want this workaround for one particular DLL
        if (e.Name != "Newtonsoft.Json")
            return null;
    
        var myLibraryFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        var path = Path.Combine(myLibraryFolder, "Newtonsoft.Json.dll");
    
        return Assembly.LoadFrom(path);
    };
    

    Notes about this workaround:

    • This code only works if it is executed in your C# library before doing anything that might cause the jitter to load the JSON library. For example, neither your library nor any other .NET library in your VB6 process must call any method referencing types from the JSON library before this code is executed.

    • You modify the the behaviour of the whole process, not just your library. If your VB6 process uses another library using JSON, your "redirect" affects the other library as well.