我一直在研究這幾天。我試圖在它自己的AppDomain下的外部程序集中正確地創建一個類的實例。在新的AppDomain下執行一個dll程序集
我已經能夠在新的AppDomain下加載外部程序集,但是它的所有依賴似乎都在父AppDomain中加載,這會破壞目的,因爲我想稍後卸載dll以釋放對它們的鎖定(插件系統)。任何想法,爲什麼它會這樣做?
public MyCustomObject BindAssembly()
{
string currentAssemblyPath = @"C:\PathToMy\Assembly";
string currentAssemblyFile = @"C:\PathToMy\Assembly\MyAssembly.dll";
AssemblyName currentAssemblyName = AssemblyName.GetAssemblyName(currentAssemblyFile);
AppDomain domain = AppDomain.CurrentDomain;
domain.AssemblyResolve += domain_AssemblyResolve;
AppDomainSetup setup = new AppDomainSetup()
{
PrivateBinPath = currentAssemblyPath,
ApplicationBase = domain.BaseDirectory,
DynamicBase = domain.SetupInformation.DynamicBase,
ShadowCopyFiles = domain.SetupInformation.ShadowCopyFiles,
CachePath = domain.SetupInformation.CachePath,
AppDomainManagerAssembly = domain.SetupInformation.AppDomainManagerAssembly,
AppDomainManagerType = domain.SetupInformation.AppDomainManagerType
};
AppDomain newDomain = AppDomain.CreateDomain("NewDomain", AppDomain.CurrentDomain.Evidence, setup);
newDomain.AssemblyResolve += newDomain_AssemblyResolve;
currentAssembly = newDomain.Load(currentAssemblyName);
// tried this too
//var obj = domain.CreateInstanceFromAndUnwrap(currentAssemblyFile, className);
// list all of the assemblies inside the custom app domain
var newDomainAssemblies = newDomain.GetAssemblies(); // (contains my loaded assembly, but not dependencies)
// list all of the assemblies inside the parent app domain
var appAssemblies = AppDomain.CurrentDomain.GetAssemblies(); // (contains my loaded assembly as well as all dependencies)
return obj as MyCustomObject;
}
// resolve dependencies in custom domain
Assembly newDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
// this never fires
AppDomain domain = (AppDomain)sender;
}
// resolve dependencies in parent domain
Assembly domain_AssemblyResolve(object sender, ResolveEventArgs args)
{
AppDomain domain = (AppDomain)sender;
string assemblyDependencyPath = String.Format(@"{0}", Path.GetDirectoryName(Uri.UnescapeDataString(new UriBuilder(args.RequestingAssembly.CodeBase).Path)));
string[] files = Directory.GetFiles(assemblyDependencyPath, "*.dll", SearchOption.AllDirectories);
foreach (string file in files)
{
// if we found it, load the assembly and cache it.
AssemblyName aname = AssemblyName.GetAssemblyName(file);
if (aname.FullName.Equals(args.Name))
{
Assembly assembly = domain.Load(aname);
//Assembly assembly = Assembly.LoadFrom(file); // also tried this, same result
return assembly;
}
}
}
之間傳遞你試過'currentAssembly = newDomain.Load(currentAssemblyName);'而不是'currentAssembly = domain.Load(currentAssemblyName);'? – Rhumborl 2014-09-26 21:39:53
我還確認,如果我卸載了我創建的新AppDomain,相關程序集仍然保留在父AppDomain中。 – 2014-09-26 21:39:54
Rhumborl - 我很抱歉,這是我的存根代碼中的一個錯字。修正了我的問題。 – 2014-09-26 21:40:43