调用AppDomain.Load()抛出System.IO.FileNotFoundException问题求助
解决AppDomain.Load()抛出FileNotFoundException的问题
嘿,我之前也踩过这个坑!你遇到的FileNotFoundException其实是因为AppDomain.Load()的工作方式和你想的不一样——它并不是直接在你创建的SecondaryDomain里加载程序集,而是先在当前应用程序域中尝试加载目标程序集,之后才会把加载好的程序集传递到你指定的新域。如果当前域找不到System.Dynamic(比如版本不匹配、搜索路径不对),就会直接抛出这个异常。
正确的做法:在目标域内加载程序集
要实现在新域中加载程序集,你需要借助MarshalByRefObject创建一个跨域对象,让加载逻辑直接在目标域内执行。这样就能确保加载上下文是正确的,不会受当前域的影响。
这里是修改后的完整代码:
using System; using System.Reflection; // 定义一个跨域对象,必须继承MarshalByRefObject public class DomainLoader : MarshalByRefObject { public void LoadAssembly(string assemblyName) { // 这里的加载操作是在目标域内执行的 Assembly.Load(assemblyName); Console.WriteLine($"在域 {AppDomain.CurrentDomain.FriendlyName} 中加载了 {assemblyName}"); } public void ListAssemblies() { foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { Console.WriteLine($"程序集名称:{assembly.GetName().Name},版本:{assembly.GetName().Version}"); } } } class Program { static void Main(string[] args) { AppDomain newDomain = AppDomain.CreateDomain("SecondaryDomain"); newDomain.AssemblyLoad += (sender, eventArgs) => Console.WriteLine($"已加载程序集:{eventArgs.LoadedAssembly.GetName().Name}"); newDomain.DomainUnload += (sender, EventArgs) => Console.WriteLine("域已卸载"); Console.WriteLine($"新域名称:{newDomain.FriendlyName}"); // 创建跨域对象,让逻辑在目标域执行 var loader = (DomainLoader)newDomain.CreateInstanceAndUnwrap( typeof(DomainLoader).Assembly.FullName, typeof(DomainLoader).FullName ); // 在目标域内加载System.Dynamic loader.LoadAssembly("System.Dynamic"); // 列出目标域中的所有程序集 Console.WriteLine("\n目标域中的程序集列表:"); loader.ListAssemblies(); // 卸载域 AppDomain.Unload(newDomain); } }
关键要点说明
MarshalByRefObject的作用:跨应用程序域调用对象方法时,必须继承这个类,它允许.NET通过代理在不同域之间传递对象引用。- 避免直接调用
AppDomain.Load():这个方法的设计初衷是从当前域向目标域传递已加载的程序集,而不是在目标域中直接加载。 - 加载上下文的重要性:程序集的加载路径、版本绑定等都是基于当前执行代码的应用程序域,所以在目标域内执行加载逻辑才能保证正确性。
内容的提问来源于stack exchange,提问作者user8531685
相关产品推荐
相关产品推荐

