Yor*_*z0r 5 c# appdomain marshalbyrefobject .net-assembly
最近我一直致力于一个项目,其中应用程序(或可执行文件,无论你想要什么)都需要能够加载和卸载在可执行文件夹中找不到的程序集.(甚至可能是另一个驱动器)
为了举个例子,我希望能够将我的应用程序放在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);
}
Run Code Online (Sandbox Code Playgroud)
尽可能具体:有没有办法让无法加载的AppDomain加载不在应用程序基础文件夹中的程序集?
每个AppDomain都有它自己的基本目录,并且完全不受主应用程序基础dir的限制(除非它是应用程序的主AppDomain).因此,您可以使用AppDomains实现您想要的功能.
您的方法不起作用的原因是您在AppDomains之间传递Assembly对象.当您调用任何GetAssembly方法时,程序集将加载到子AppDomain中,但是当方法返回时,主AppDomain也将尝试加载程序集.当然,程序集将无法解析,因为它不在主AppDomains的基本目录,私有路径或GAC中.
所以一般来说,你不应该在它们之间传递Type或Assembly反对AppDomains.
在这个答案中可以找到一种加载程序集而不将它们泄漏到主AppDomain的简单方法.
当然,为了使您的应用程序能够在子AppDomain中加载程序集,您必须创建MarshalByRefObject将成为AppDomains之间的访问点的派生类.