A friend of mine (who apparently refuses to blog, but I'll link out to him anyway since he's one of my homies) is working on a new app with a “plugin” architecture. I love that kind of stuff. One of his plugins has a dependency on another assembly. Things were not working well - even when he attempted to load the dependent assemblies into the AppDomain. We hunted around to find a solution and came accross a cool new event I was not aware of before - the AssemblyResolve event.
Anyway, here's the low-down on the entire process he was doing originally (which didn't work):
- Load the plugin assembly into the current AppDomain.
- Check for dependencies via GetReferencedAssemblies on the newly loaded assembly.
- Check each of the referenced assemblies by the plugin assembly against the loaded assemblies in the current AppDomain.
- If a referenced assembly is not loaded in the current AppDomain then load the referenced assembly.
- Create an instance of the base type in plugin assembly via an Activator <-- This failed for assemblies with dependent assemblies (that were not already loaded in the current AppDomain, so we're not talking about assemblies in the BCL or anything)
So, after some searching around, I came accross the AssemblyResolve event, which is part of the AppDomain class. This worked - and it is cool. The AssemblyResolve event occurs when the resolution of an assembly fails. The handler receives an argument of ResolveEventArgs which contains the name of the assembly that failed to resolve. The signature of the handler indicates that an assembly is the return type. Basically, all you do is resolve the assembly yourself and return the loaded assembly when the AssemblyResolve event is raised. So cool, and easy too.
I love learning new things - maybe that is why I love .NET. There is so much in the framework that there is always new things to learn. Always new things I didn't know were there before.