Ahm*_*lal 9 c# appdomain appdomainsetup
我正在使用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);
Run Code Online (Sandbox Code Playgroud)
在我创建的AppDomain上使用Load时,我一直收到File not found异常.
谢谢.
尝试从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
Run Code Online (Sandbox Code Playgroud)
CurrentDomain_AssemblyResolve每次调用方法时都会调用该AppDomain.CurrentDomain.Load("...")方法.此自定义事件处理程序使用您自己的自定义逻辑来执行定位程序集的任务(这意味着您可以将其指向任何位置,甚至在bin路径之外等).我希望这能节省几个小时......
我想我已经弄清楚为什么会发生这种情况,那是因为当前域也需要加载程序集,即使你在不同的应用程序域中加载程序集,当前域需要知道它并加载它,那是因为如何.NET的设计.
点击此处了解详情.
http://msdn.microsoft.com/en-us/library/36az8x58.aspx
当我检查了融合日志时,我发现新创建的应用程序域成功地能够从私有bin路径加载程序集,以及为什么你仍然得到"File not found"的例外,因为这个异常最初属于到当前的应用程序域.
这意味着如果您将程序集复制到当前应用程序路径或当前域探测的路径,您会发现可以将程序集加载到自定义域中.
希望有所帮助.