6

所以最近我一直在研究一个项目,其中应用程序(或可执行文件,无论你想怎么称呼它)需要能够加载和卸载在可执行文件文件夹中根本找不到的程序集。(甚至可能是另一个驱动器)

举个例子,我希望我的应用程序位于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 加载不在应用程序基本文件夹中的程序集?

4

2 回答 2

7

每个AppDomain都有自己的基本目录,并且完全不受主应用程序基本目录的限制(除非它是应用程序的主 AppDomain)。因此,您可以使用 AppDomains 实现您想要的。

您的方法不起作用的原因是您在 AppDomain 之间传递 Assembly 对象。当您调用任何GetAssembly方法时,程序集将加载到子 AppDomain 中,但是当方法返回时,主 AppDomain 也会尝试加载程序集。当然,程序集不会被解析,因为它不在主 AppDomain 的基本目录私有路径GAC中。

所以一般来说你不Type应该AssemblyAppDomains.

可以在此答案中找到一种加载程序集而不将它们泄漏到主 AppDomain 的简单方法。

当然,要使您的应用程序与加载在子 AppDomain 中的程序集一起工作,您必须创建MarshalByRefObject派生类作为 AppDomain 之间的访问点。

于 2013-10-11T10:47:19.063 回答
-5

也许您需要使用全局变量,所以如果您使用全局变量来解决问题,您可以声明只读全局变量,例如:

public static string a = "Moosaie";

将其转换为

public static readonly a = "Moosaie";

无论如何,您不能将全局动态值变量用于 CLR 程序集。

于 2015-07-15T09:47:40.957 回答