Unload COM dll from .Net program
We have a .Net application from which a C++ COM component is being instantiated. We load the COM component from a child form window. There is a common resource that is being edited by the .Net application, which inturn is being used by the COM dll to start up.
When the following sequence of steps are performed:
1. Instantiate COM component in the new child window The COM component is instantiated, and is used by the child form , and after being used, it is being set to NULL , hoping that the COM component would be unloaded.
2. Keep child window open, and then edit the resource
3. Now, go and "refresh" the form, to create a new COM instance, to see the refelection of the changed resource - but the resource is not refreshed.
We also used Marshal.ReleaseComObject method, but to no success. Please advice.
No correct solution
Once a DLL is loaded into a .Net AppDomain, it is not possble to force a DLL to be unloaded. It's an unfortunate limitation of the CLR. If you absolutely need the DLL to unload you can do the following.
- Create a new AppDomain
- Load the DLL into the new DLL
- Do the work in the new AppDomain
- Unload the new AppDomain
If a DLL is only loaded in one AppDomain, unloading the AppDomain will unload the DLL as well. So this will get the DLL unloaded. However it is a pretty heavyweight answer.
COM object and DLL are two different things, even if one resides in another. Certain hacks are possible, but much better solution is to rewrite this part in a more sensible way which doesn't rely on DLL unloading.
A discussion on clrInterop page describes very close what you outlined in your question. The garbage collector does not unload the native dll. I quote: " It could be very dangerous for clr to do this because there might be other code (even native code) which depends on that dll. If you do assure that dll is not used any more, calling a windows API like FreeLibrary may be easiest way to unload the dll."
So you'll need to interop FreeLibrary and use that to unload the native dll. Although I might add: don't if you can try to find a solution where you don't need to unload the dll.