您可以創建新的AppDomain的實例,該實例中執行代碼。
var settings = new AppDomainSetup
{
ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
};
var childDomain = AppDomain.CreateDomain(Guid.NewGuid().ToString(), null, settings);
var handle = Activator.CreateInstance(childDomain,
typeof(ReferenceLoader).Assembly.FullName,
typeof(ReferenceLoader).FullName,
false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.CurrentCulture, new object[0]);
var loader = (ReferenceLoader)handle.Unwrap();
//This operation is executed in the new AppDomain
var paths = loader.LoadReferences(assemblyPath);
AppDomain.Unload(childDomain);
這裏是ReferenceLoader
public class ReferenceLoader : MarshalByRefObject
{
public string[] LoadReferences(string assemblyPath)
{
var assembly = Assembly.ReflectionOnlyLoadFrom(assemblyPath);
var paths = assembly.GetReferencedAssemblies().Select(x => x.FullName).ToArray();
return paths;
}
}
謝謝,這看起來像一個有用的模式。 – 2009-01-07 09:28:32
Assembly.RefrectionOnlyLoad(...)是否仍然在當前域中加載程序集,而不是在TemporaryAppDomain中? – Anzurio 2009-05-30 18:59:58
AZ:否。AppDomain.DoCallback「執行由指定委託標識的另一個應用程序域中的代碼」(MSDN)。 Assembly的文檔。ReflectionOnlyLoad明確指出「程序集加載到調用者應用程序域的僅反射上下文」(再次,MSDN)。這意味着程序集確實已加載到臨時應用程序域。 – 2009-05-30 20:15:57