实际上,我尝试在我的解决方案中实现某种“静态链接”程序集。所以我尝试了以下方法:
- 使用 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 中的资源文件加载程序集。但只有当它在其他地方找不到我的程序集时,才会发生此事件。但是我怎样才能加载我的程序集before.Net尝试搜索不同的地方?
由于事实来自检查以前引用的程序集 http://msdn.microsoft.com/en-us/library/aa98tba8.aspx我认为可以预先将程序集加载到域中,并且可以这样做。
我使用以下 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 时,我也返回了 null,但在这种情况下,我在开始时得到了 FileNotFoundException。