c# Assembly.LoadFrom with dynamic AssemblyResolve

401 Views Asked by At

I'm kind of stuck with dynamically loading plugins:

Theory: (Plugin) Dlls in a specific folder:

foreach(string path in Directory.GetFiles(...))
{
    Assembly myPlugin = Assembly.LoadFrom(path);
    foreach(Type type in myPlugin.GetTypes().Where(t => typeof(myPluginBaseClass).isAssignableFrom(t)))
    {
        Activator.CreateInstance(type);
    }
}

So far so good. Now there are issues with additional references in those assemblies, which can be solved by catch(ReflectionTypeLoadException) (to removed all null Types) and AppDomain.CurrentDomain.AssemblyResolve += ... (to manually look for those missing dlls)

Now here is the issue: The referenced missing assemblies are specific for each implemented Plugin, so I need a individual search behavior implemented in each Plugin. My ideas / solutions so far:

  • Having a global list of all possible DLL directories in my main application -> stupid because this won't allow to add further plugins without changing the main application code
  • Having a (non static) dictionary of specific dll paths in each plugin -> can be forced by the myPluginBaseClass using virtual/abstract; But can't be accessed before creation of the instance (where those AssemblyResolveEvents are fired), so not helpful
  • Having a (static) dictionary of specific dll paths in each plugin -> can be read before instantiation by using Reflection, but I can't add this to my myPluginBaseClass as a defined template, so errors possible
  • Creating a individual Domain for each plugin and let them handle their own AssemblyResolveEvent -> But how?

I hope you can help!

Thanks in advance! Robin

1

There are 1 best solutions below

1
Tony THONG On

Create domain seems to be adequat solution for plugin pattern.

You don't really need to define AssemblyResolve, you can simply configure the directory where AppDomain can find dependencies.

https://msdn.microsoft.com/fr-fr/library/system.appdomainsetup.applicationbase(v=vs.110).aspx