c# - 如何在 AssemblyResolve 事件之前在运行时加载程序集?

标签 c# .net-3.5 assemblies

实际上,我试图在我的解决方案中实现某种“静态链接”程序集。所以我尝试了以下方法:

  • 使用 CopyLocal = false 添加对我的程序集的引用
  • 使用“添加为链接”将 .dll 文件本身添加到我的解决方案
  • 使用“添加资源”-“添加现有文件”将 .dll 文件本身添加到我的资源
  • 将我的程序集中的一些类型添加到 Form1 中作为 private MyObject temp = new MyObject();

完成这些步骤后,我得到了预期的 FileNotFoundException。因此,让我们尝试使用这个快速技巧在 AssemblyResolveEvent 中加载程序集

AppDomain.CurrentDomain.AssemblyResolve += (sender, e) =>
    {
        Assembly MyAssembly = AppDomain.CurrentDomain.Load(Properties.Resources.ExternalAssembly);
        return MyAssembly;
    };

所以这行得通!我能够从 AssemblyResolveEvent 中的资源文件加载我的程序集。但是只有当它在其他任何地方都找不到我的程序集时,才会发生此事件。但是我怎样才能让我的程序集在 .Net 尝试搜索不同的地方之前加载??

由于来自 Checking for Previously Referenced Assemblies 的事实我认为可以预先将程序集加载到域中,这将被采用。

我通过使用以下 Main() 方法在 program.cs 中尝试了这一点

static void Main()
{
    LoadMyAssemblies();
    AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => LoadMyAssemblies();
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}

private static Assembly LoadMyAssemblies()
{
    Assembly result = AppDomain.CurrentDomain.Load(Properties.Resources.MyStaticAssembly);
    return result;
}

但它仍然会遇到 ResolveEventHandler。更好的是,如果我再次加载程序集并查看 AppDomain.CurrentDomain.GetAssemblies(),我可以看到我的程序集被加载了两次!!

所以知道为什么我加载的程序集在 AssemblyResolve 事件之前加载时不会被考虑在内吗?在调试器的帮助下,当调用来自 AssemblyResolve 时,我也返回了一个空值,但在这种情况下,我在开始时得到了一个 FileNotFoundException。

最佳答案

万一你不知道,有一个工具叫做 ILMerge来自 MS Research,它将程序集合并到一个文件中。

您还可以使用 Assembly Linker tool 创建多文件程序集.

加上回答你原来的问题,我认为问题是运行时不知道你手动加载的程序集是它应该寻找的那个。因此,在程序集解析事件中,无需再次加载程序集,只需将引用传递回您已手动加载的程序集即可。

关于c# - 如何在 AssemblyResolve 事件之前在运行时加载程序集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1159192/

相关文章:

c# - C# 中的枚举助手未给出预期结果

.net-3.5 - 如何找出哪些进程锁定了文件夹或文件?

.net - 即使缺少依赖 dll 也能启动 exe 吗?

c# - Unity 编辑器在使用 mfperfhelper.dll 访问冲突时崩溃

c# - 在插件框架中使用抽象类作为契约

wpf - 我无法在库项目中添加对命名空间 system.windows.controls 的引用

c# - 引用 dll 而不复制它们 C#

c# - 有选择地隐藏 C# 图表中的系列

c# - 从实现类中的接口(interface)继承注释?

c# - Dictionary ToList 序列化问题