I'm using the following unmanaged C++ code to instantiate the CLR from an Excel 2003 add-in (a COM shim for a .NET add-in):
hr = CorBindToRuntimeEx(
0, // version, use default
0, // flavor, use default
0, // domain-neutral"ness" and gc settings
CLSID_CorRuntimeHost,
IID_ICorRuntimeHost,
(PVOID*) &m_pHost);
and for the vast majority of the machines in our organisation (a few hundred) this works perfectly, even those with multiple CLR versions installed; however for a few machines a wrong (older) version of the CLR is instantiated which then fails to load the assembly as it requires the .NET 2 runtime.
Yesterday for the first time I ran Process Explorer and this was quite revealing showing the following on one of the problem machines:
process pid type Handle or DLL
------- --- ---- -------------
procexp.exe 5056 DLL c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorworks.dll
EXCEL.EXE 7180 DLL c:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\mscorworks.dll
i.e. Excel has loaded the wrong version of the runtime even though a newer one is availble. Now I need to find out why.
A few possibilities that come to mind:
I strongly suspect the second of these but don't know how to prove / fix it.
Has anyone seen similar behaviour? Any suggestions on what is going on?
A few other notes:
I can't change either of these so a newer Excel version is not an option.
This is the infamous CLR version injection problem. This is the somewhat mild kind as opposed to the really nasty kind you get when you write a shell extension in .NET.
Problem is that there was an add-in that loaded before yours and it asked for the 1.1 version of the CLR to be loaded. That's where the buck stops, a process can have only one version of the CLR. You can ask for the 2.0.50727 version to be loaded in your CorBindToRuntimeEx() call, that's the one you need for your add-in. But that will fail. Asking for the default version will succeed but now your add-in will fail to load.
The 'something mild' angle is that you could technically change the order in which add-ins get loaded, ensuring that CLR 2.0 gets loaded first. Not actually sure how to do this. The add-in that requires 1.1 has reasonable odds of still working correctly. Ask at superuser.com if that's what you want to do.
There's a long term solution, CLR version 4 supports in-process side-by-side versioning of the CLR. Not something that will help you right now.
Can you use GetCORVersion to check if the CLR has already been loaded? And if GetCORVersion returns v1.x as the loaded CLR version, abort loading the CLR and present an error message to the user.
Is migrating your add-in to .net v4 an option? v4 supports in-process side-by-side hosting of CLR ((v1.x OR V2) AND V4 and newer). Look at CLRCreateInstance.
References:
CLR Hosting Overview
In-Process Side-by-Side
@ MSDN Magazine
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With