[英]Loading an assembly into an AppDomain outsite of applicationBase C#
最近我一直致力于一个项目,其中应用程序(或可执行文件,无论你想要什么)都需要能够加载和卸载在可执行文件夹中找不到的程序集 。 (甚至可能是另一个驱动器)
为了举个例子,我希望能够将我的应用程序放在D:\\ AAA \\ theAppFolder中 ,并将DLL文件的程序集放在C:\\ BBB \\ Assemblies
仔细观察,我发现AppDomain允许卸载自己和任何附加程序集的能力,所以我想我会试一试,但是经过几个小时的尝试后似乎有问题:AppDomains看不到外面的任何地方应用基础。
根据AppDomain的纪录片(以及我自己的经验)你不能在ApplicationBase之外设置PrivateBinPath,如果我在应用程序所在的驱动器之外设置ApplicationBase(通过AppDomainSetup),我得到System.IO.FileNotFoundException抱怨它不能找到应用程序本身。
因此我甚至无法达到可以使用AssemblyResolve ResolveEventHandler尝试使用MarhsalByRefObject继承类来获取程序集的阶段...
这里有一些与我目前正在尝试的代码相关的代码片段
internal class RemoteDomain : MarshalByRefObject
{
public override object InitializeLifetimeService() //there's apparently an error for marshalbyref objects where they get removed after a while without this
{
return null;
}
public Assembly GetAssembly(byte[] assembly)
{
try
{
return Assembly.Load(assembly);
}
catch (Exception e)
{
Console.WriteLine(e);
}
return null;
}
public Assembly GetAssembly(string filepath)
{
try
{
return Assembly.LoadFrom(filepath);
}
catch (Exception e)
{
Console.WriteLine(e);
}
return null;
}
}
public static Assembly LoadAssembly(string modName, BinBuffer bb)
{
string assembly = pathDirTemp+"/"+modName+".dll";
File.WriteAllBytes(assembly, bb.ReadBytes(bb.BytesLeft()));
RemoteDomain loader = (RemoteDomain)modsDomain.CreateInstanceAndUnwrap(typeof(RemoteDomain).Assembly.FullName, typeof(RemoteDomain).FullName);
return loader.GetAssembly(assembly);
}
尽可能具体: 有没有办法让无法加载的AppDomain加载不在应用程序基础文件夹中的程序集?
每个AppDomain
都有自己的基本目录,并不受主应用程序基础dir的约束(除非它是应用程序的主AppDomain)。 因此,您可以使用AppDomains实现您想要的功能。
您的方法不起作用的原因是您在AppDomains之间传递Assembly对象。 当您调用任何GetAssembly
方法时,程序集将加载到子AppDomain中,但是当方法返回时,主AppDomain也将尝试加载程序集。 当然,程序集将无法解析,因为它不在主AppDomains的基本目录 , 私有路径或GAC中 。
因此,通常不应在AppDomains
之间传递Type
或Assembly
对象。
在这个答案中可以找到一种加载程序集而不将它们泄漏到主AppDomain的简单方法。
当然,为了使您的应用程序能够在子AppDomain中加载程序集,您必须使MarshalByRefObject
派生类成为AppDomains之间的访问点。
也许您需要使用全局变量,因此如果您使用全局变量来修复问题,您可以声明readonly全局变量,例如:
public static string a = "Moosaie";
将其转换为
public static readonly a = "Moosaie";
无论如何,您不能将全局动态值变量用于CLR程序集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.