9

我使用 c# 4.0 和一个控制台应用程序只是为了测试,下面的代码确实给出了一个异常。

AppDomainSetup appSetup = new AppDomainSetup()
{
    ApplicationName = "PluginsDomain",
    ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
    PrivateBinPath = @"Plugins",
    ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
};

AppDomain appDomain = AppDomain.CreateDomain("PluginsDomain", null, appSetup);

AssemblyName assemblyName = AssemblyName.GetAssemblyName(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins", "sample.dll"));

Assembly assembly = appDomain.Load(assemblyName); //This gives an exception of File not found

AppDomain.Unload(appDomain);

在我创建的 AppDomain 上使用Load时,我不断收到 File not found 异常。

谢谢。

4

3 回答 3

10

首先确保 Plugins 是AppDomain基本路径的子目录。仅适用于此处PrivateBinPath描述的子目录

如果这不是问题,请查看您的融合绑定日志。使用融合日志查看器还有一篇很好的博客文章。融合日志将告诉您它在哪里搜索程序集。这应该告诉您您的路径是否包含在搜索中。

其他可能性之一是它正在查找您的程序集,但不是它的依赖项之一。融合日志查看器会再次告诉您。

于 2011-07-08T20:00:14.777 回答
9

我在尝试从 bin 目录之外的目录动态加载 dll 文件时遇到了这个线程。长话短说,我能够通过使用该AppDomain.CurrentDomain.AssemblyResolve事件来实现这一点。这是代码:

//--begin example:

public MyClass(){
    AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}

private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    foreach (var moduleDir in _moduleDirectories)
    {
        var di = new DirectoryInfo(moduleDir);
        var module = di.GetFiles().FirstOrDefault(i => i.Name == args.Name+".dll");
        if (module != null)
        {
            return Assembly.LoadFrom(module.FullName);
        }
    }
    return null;
}

//---end example

CurrentDomain_AssemblyResolve每次调用该方法时都会调用该AppDomain.CurrentDomain.Load("...")方法。此自定义事件处理程序使用您自己的自定义逻辑执行定位程序集的工作(这意味着您可以告诉它查看任何地方,甚至在 bin 路径之外等)。我希望这可以节省其他人几个小时...

于 2013-05-22T19:43:01.863 回答
6

我想我已经弄清楚为什么会发生这种情况,那是因为即使您在不同的应用程序域中加载程序集,当前域也需要加载程序集,当前域需要知道它并加载它,那是因为如何.NET 被设计出来。

在这里查看详细信息。

http://msdn.microsoft.com/en-us/library/36az8x58.aspx

而当我查看融合日志时,发现新创建的app域成功地能够从私有bin路径加载程序集,以及为什么你仍然得到“找不到文件”的异常,因为这个异常原本属于到当前的应用程序域。

这意味着如果您将程序集复制到当前应用程序路径或当前域正在探测的路径中,您会发现您可以将程序集加载到您的自定义域中。

希望有帮助。

于 2011-07-12T00:20:52.647 回答