Problems loading assembly dependencies dynamically at run-time

邮差的信 提交于 2019-11-30 23:34:51

You can set the probing path of the runtime so it can find the assemblies. Set the probing element in your apps config file.

<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <probing privatePath="plugins;dependencies"/>
    </assemblyBinding>
  </runtime>
</configuration>

The AssemblyResolve event happens when the framework tries to load an assembly, and fails.

What this means is that if it's giving you Presentation.Zune.dll in the args, that the framework can't find that assembly, and this is your chance to intercept it and do other things, like load it from a directory that the framework might not know about - eg your plugins\dependencies folder...

Off the top of my head, I'd try something like this:

Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    if( File.Exists(".\\Plugins\\"+args.Name) )  // it's a plugin
        return Assembly.Load(".\\Plugins\\"+args.Name);
    else if( File.Exists(".\\Plugins\\Dependencies\\"+args.Name) )  // it's a dependency OF a plugin
        return Assembly.Load(".\\Plugins\\Dependencies\\"+args.Name);
    else
        throw new Exception();
}

BTW: You can speed up loading assemblies considerably if you cache your assemblies that you already resolved in a Dictionary. If A depends on B, C and B depends on C and you load A, AssemblyResolve will be called twice for C, and loading the assembly only once is faster :)

(I am not sure if it is always the case that AssemblyResolve is called more than once, but I noticed it when debugging a project once. And it does not hurt to cache the assemblies...)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!