

新闻资讯
技术学院Assembly.LoadFile 是 C# 中按文件路径动态加载程序集的方法,但不会自动解析依赖项;需手动处理依赖,如放置于 bin 目录、订阅 AssemblyResolve 事件或改用 AssemblyLoadContext。
Assembly.LoadFile 是 C# 中用于从指定文件路径动态加载程序集(.dll 或 .exe)的方法,它会将程序集加载到当前上下文(LoadContext),但**不会自动解析其依赖项**——这是使用时最容易出错的关键点。
假设你有一个外部类库 MyPlugin.dll,其中包含一个公开类 MyPlugin.Service:
Assembly.LoadFile(path) 获取程序集对象assembly.GetType("FullName") 获取类型,再通过 Activator.CreateInstance 创建实例string dllPath = @"C:\Plugins\MyPlugin.dll";
Assembly assembly = Assembly.LoadFile(dllPath);
Type serviceType = assembly.GetType("MyPlugin.Service");
object instance = Activator.CreateInstance(serviceType);
// 调用方法(需反射或接口约定)
serviceType.GetMethod("DoWork").Invoke(instance, null);
LoadFile 只加载指定文件,不处理它引用的其他程序集(比如它
依赖 Newtonsoft.Json.dll)。如果缺失依赖,运行时会抛出 FileNotFoundException 或 FileLoadException。
bin 目录(让默认 AssemblyResolve 机制找到)AppDomain.CurrentDomain.AssemblyResolve 事件,手动返回依赖程序集AssemblyLoadContext.LoadFromAssemblyPath,更可控且支持隔离LoadFile:按文件路径加载,不考虑 GAC 或加载上下文策略;同一程序集多次调用会重复加载(不同 Assembly 实例)LoadFrom:也按路径加载,但会触发上下文绑定,可能复用已加载的程序集,且会尝试解析依赖(行为较复杂)Load:按 AssemblyName 加载,走 GAC / bin / probing path,无法直接指定任意磁盘路径LoadFile(存在代码执行风险)IPlugin 在主程序中),用强类型交互替代纯反射AssemblyLoadContext,支持卸载(Unload),避免内存泄漏assembly.GetReferencedAssemblies() 查看它依赖哪些程序集基本上就这些。用对场景、管好依赖、注意上下文,LoadFile 就很可靠。