我试图在我的解决方案中实现某种“静态链接”程序集,所以我尝试了以下操作:
- 将引用我的程序集添加到解决方案中,并设置CopyLocal = false
- 使用“作为链接添加”将.dll文件本身添加到我的解决方案中
- 使用“添加资源” - “添加现有文件”将.dll文件本身添加到我的资源中
- 将我的程序集中的某些类型作为
private MyObject temp = new MyObject();
添加到Form1中
经过这些步骤后,我得到了预期的FileNotFoundException。因此,让我们尝试使用快速技巧在AssemblyResolveEvent中加载程序集。
AppDomain.CurrentDomain.AssemblyResolve += (sender, e) =>
{
Assembly MyAssembly = AppDomain.CurrentDomain.Load(Properties.Resources.ExternalAssembly);
return MyAssembly;
};
所以这个方法能够工作!我能够从资源文件中加载我的程序集,并在AssemblyResolveEvent中使用它。但是,如果在其他任何地方找不到我的程序集,才会触发此事件。但是我该如何让我的程序集在.Net尝试搜索其他地方之前被加载呢?由于来自检查先前引用的程序集的事实,我认为预先将程序集加载到域中是可能的,并且这将被采用。
我尝试在 program.cs 中使用以下 Main() 方法实现此目的。
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 调用返回 null 时,我也返回了 null,但在这种情况下,我得到了 FileNotFoundException。