I was recently debugging a code that was trying to load a native Dll using LoadLibrary within ASP.NET process. The code was trying a load native Dll and then dynamically invoke a method by name using GetProcAddress. The loadlibrary code was working as expected within a managed Dll and was also tested with in a console application. But it started throwing exception when it was used by the ASP.NET process. Debugged and figured out the exception was FileNotFoundException for loading the Dll via LoadLibrary. The Dll was copied into the bin folder in spite of it the ASP.NET runtime didn’t copy the Dll to the shadow location. After doing a research figured out the runtime would copy dependencies that have been referenced by the code and referenced via PInvoke, and that was the reason the Dll wasn’t copied.
So I had three choices
- Copy the native Dll’s to system32 directory – Certainly wasn’t a good idea
- Change the native code to implement COM – So that the Dll can be in any location and the ASP.NET can still load them. This wasn’t possible because we didn’t have source code
- Add the path of the Dll to the environment path variable – This was the most viable solution. The one drawback with this solution was if there was another native Dll with the similar name and if it was found in lookup then that would be loaded.
So we went ahead took the third option and renamed the Dll to include the organization name. The loadlibrary code within the ASP.NET runtime was able to locate the native Dll and load it.
FYI if the path environment variable is updated then the IIS has to be restarted to load the updated path variable.