Nick and I had a heck of a time today trying to load an assembly into an application.  Sounds pretty straight forward, don’t it?  Well, it’s harder than you might think.  We took two approaches to the problem: use a new AppDomain and load from it or load using the Assembly class.

The first approach was pretty straight forward.  Create an AppDomainSetup object and set it’s ApplicationBase, ApplicationName, PrivateBinPath and PrivateBinPathProbe properties to the directory path where your desired assembly lives.  Next using the CreateDomain method from the AppDomain class, give the new domain a name and pass it the newly created domain setup object.  After all this is done, you can load an assembly into that app domain! (or so you think!)  To load an assembly, call the Load method on your AppDomain instance.  And voila, an error!  I do not recall the exact text of the exception, but I do recall that it was a serialization issue.

In reality, it’s a hidden FileNotFoundException that caused the problem.  Why?  Well, as it turns out, your assembly loads successfully into your new AppDomain.  You can verify this by using the Fusion Log viewer (to setup the viewer, check out an earlier post) and selecting the entry named like your ApplicationName property.  But you will also see that you have your calling assembly tries to load the exact same assembly and fails.  Why?  Well, it needs to reference it so it can provide you with a valid Assembly object.  The loading fails since your calling AppDomain can’t find the assembly under it’s probing path (the directory in which the application is under).  So, since it can’t load it, it cannot serialize the assembly reference from created app domain to calling app domain.  Clear as mud?  If you have any questions, please feel free to contact me.

Our second approach was a bit more straight forward.  We just called the LoadFile method on the Assembly class giving it the full path to the assembly file (i.e. c:\directory\assembly.dll).  Result?  It worked!…in some instances.  For some reason some of the referencing assemblies for the loading assembly (assembly.dll) couldn’t be found!  Although they were in the same location and the loading assembly!!  So, we went back to the log viewer and saw that the referencing assemblies that failed to load were being probed under a different application base path.  The interesting thing about all of this is that this procedure worked for other assemblies in that same folder!!  Weird, huh?

Ok, and now to my point of this post…I know, I know, I tell long stories…I am posting this so you, my three readers, can have this as a reference and avoid all of this pain.  Nick and I still need to resolve the loading issue since we need this mechanism to work for a big part of our project.  I will keep you updated on the outcome of the situation as we proceed on the search for a meaningful answer.

For now, keep on probing!