假设有2个DLL, Class1和Class2. Class1引用Class2, 并调用Class2里的方法。
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
//Class1.Dll
namespace feiyun0112.cnblogs.com
{
public class Class1
{
public void DoSomething() { Class2.Hello(); }
}
}
//Class2.Dll
namespace feiyun0112.cnblogs.com
{
public class Class2
{
public static void Hello() { MessageBox.Show("Hello World!"); }
}
}
如果我们动态调用Class1里的方法,会报无法加载"Class2"的异常
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
string path = @"C:\test\Class1.dll";
Assembly assembly = Assembly.LoadFile(path);
Type type = assembly.GetType("feiyun0112.cnblogs.com.Class1");
object obj = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod("DoSomething", BindingFlags.Public | BindingFlags.Instance);
if (method != null)
{
method.Invoke(obj, null);
}
解决的方法其实也很简单,在对程序集的解析失败时, 会触发AppDomain.AssemblyResolve事件, 我么只需要在事件中进行处理,
将需要的Dll加载到应用程序域,动态调用的程序集就可以正常使用了。
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
{
string strFielName = args.Name.Split(',')[0];
return Assembly.LoadFile(string.Format( @"C:\test\{0}.dll",strFielName));
}