方法 (b) 失败,因为AppDomain.Load无法解析不在基本应用程序目录、探测私有路径或 GAC 中的程序集。
另请注意,AppDomain.Load
没有在特定的 AppDomain 上加载程序集(如您adapterDomain.Load
的示例代码中)。相反,它将它加载到当前的 AppDomain 上(这是调用.MSDN 文档AppDomain.Load
的那个。)显然这不是您要寻找的。
下面是一个关于如何在子 AppDomain 中调用静态方法的示例:
class Program
{
static void Main(string[] args)
{
// This is for testing purposes!
var loadedAssembliesBefore = AppDomain.CurrentDomain.GetAssemblies();
var domain = AppDomain.CreateDomain("ChildDomain");
// This will make the call to the static method in the dhild AppDomain.
domain.DoCallBack(LoadAssemblyAndCallStaticMethod);
// Print the loaded assemblies on the child AppDomain. This is for testing purposes!
domain.DoCallBack(PrintLoadedAssemblies);
AppDomain.Unload(domain);
// This is for testing purposes!
var loadedAssembliesAfter = AppDomain.CurrentDomain.GetAssemblies();
// Assert that no assembly was leaked to the main AppDomain.
Debug.Assert(!loadedAssembliesBefore.Except(loadedAssembliesAfter).Any());
Console.ReadKey();
}
// Loads StaticMethodInHere.dll to the current AppDomain and calls static method
// StaticClass.DoSomething.
static void LoadAssemblyAndCallStaticMethod()
{
var assembly = Assembly.LoadFrom(@"PATH_TO_ASSEMBLY");
assembly.GetType("CLASS_CONTAINING_STATIC_METHOD")
.InvokeMember("STATIC_METHOD",
BindingFlags.Public |
BindingFlags.Static |
BindingFlags.InvokeMethod,
null,
null,
null);
}
// Prints the loaded assebmlies in the current AppDomain. For testing purposes.
static void PrintLoadedAssemblies()
{
Console.WriteLine("/ Assemblies in {0} -------------------------------",
AppDomain.CurrentDomain.FriendlyName);
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
Console.WriteLine(assembly.FullName);
}
}
}
要完成这项工作,您需要更换:
- PATH_TO_ASSEMBLY 包含包含扩展的静态方法的程序集的路径。
- CLASS_CONTAINING_STATIC_METHOD 带有包含静态方法的类的名称,包括类的命名空间。
- STATIC_METHOD 带有静态方法的名称。
请注意,它们BindingFlags
是为公共静态方法设置的。