如何加载依赖程序集?

pra*_*mod 4 c# reflection

我有一个项目处理器,它依赖于其他2个项目.

当我编译项目时,我得到DLL文件夹和其他项目的依赖于Bin文件夹中的DLL.Processor.dll BusinessAction.dll和Repository.dll.

我尝试通过启动类型ProcessRequest类从Processor.dll调用方法.

像这样

 Assembly processorAssembly = Assembly.LoadFile(path + "Processor.DLL"));

        Type myType= processorAssembly.GetType("Namespace.ProcessRequest");

        myType.InvokeMember("Process", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, submitOfferType, new object[] { 12345 });
Run Code Online (Sandbox Code Playgroud)

Process方法有一些逻辑可以处理并保存到数据库中.

当我使用InvokeMember()调用procee方法时

我得到异常无法加载文件或程序集'Namespace.BusinessAction,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'或其依赖项之一.该系统找不到指定的文件.

我是在调用方法吗?

小智 8

如果找不到引用,Appdomain会触发一个事件:

AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
Run Code Online (Sandbox Code Playgroud)

在事件处理程序中,您可以手动搜索程序集:

Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    string s = @"C:\lib\" + args.Name.Remove(args.Name.IndexOf(',')) + ".dll";
    return Assembly.LoadFile(s);
}
Run Code Online (Sandbox Code Playgroud)