Search code examples
excelcom.net-4.0excel-2007com-interop

Asssembly.LoadFrom fails when called via Excel 2007


I have a .NET 4.0 class that uses Assembly.LoadFrom to load a .NET 3.5 mixed mode assembly. When this class is called from a .NET 4.0 app (with useLegacyV2RuntimeActivationPolicy="true" specified in the config file) it all works fine.

However, this class is also COM visible, and when I then call it from Excel 2007 (again, Excel.exe.config specifies useLegacyV2RuntimeActivationPolicy="true") I get a FileLoadException:

Could not load file or assembly 'Foo...' or one of its dependencies. Failed to load the runtime. (Exception from HRESULT: 0x80131700)

The inner exception is a System.Runtime.InteropServices.COMException: Failed to load the runtime. (Exception from HRESULT: 0x80131700)

I do not get this problem when calling from Excel 2003 or Excel 2010 or vbscript. Can someone explain what is going on and how I can fix it?


Solution

  • I've discovered from Microsoft that this is a known issue with Excel 2007. The problem has been resolved in Excel 2010, and the issue will not be fixed in Excel 2007.

    The workaround is to force Excel to use a COM-exposed .NET 2.0 type before using the .NET 4.0 class. I did this by adding a reference to the .NET 2.0 version of mscorlib.tlb, and then adding the following VBA code before calling the .NET 4.0 class:

    Dim o as mscorlib.Object
    Set o = New mscorlib.Object
    

    Hope this proves useful to anyone who stumbles across this obscure issue!