c# - 将程序集加载到 AppDomain

标签 c# assemblies appdomain

如果我用

Assembly assembly = Assembly.LoadFrom(file);

稍后尝试使用该文件时,我收到一个异常,指出该文件正在使用中。

我需要将它加载到一个新的应用程序域。

我似乎找到的只是如何在程序集中创建实例的示例, 有没有办法加载整个程序集

我需要的是:

 (1) load the assembly into a new AppDomain from a file . 
 (2) extract an embedded  resource (xml file) from the Dll .
 (3) extract a type of class which implements an interface (which i know the interface type) .
 (4) unload the entire appdomain in order to free the file .  

2-4不是问题

我似乎无法找到如何将程序集加载到新的 AppDomin 中,只有示例 创建实例,它为我提供了 Dll 中类的实例。

我需要全部。

就像这个问题:创建实例的另一个例子。

Loading DLLs into a separate AppDomain

最佳答案

最基本的多域场景是

static void Main()
{
    AppDomain newDomain = AppDomain.CreateDomain("New Domain");
    newDomain.ExecuteAssembly("file.exe");
    AppDomain.Unload(newDomain);
}

在单独的域上调用 ExecuteAssembly 很方便,但不提供与域本身交互的能力。它还要求目标程序集是可执行文件,并强制调用者使用单个入口点。为了增加一些灵 active ,您还可以将字符串或参数传递给 .exe。

希望对您有所帮助。

扩展:然后尝试类似下面的操作

AppDomainSetup setup = new AppDomainSetup();
setup.AppDomainInitializer = new AppDomainInitializer(ConfigureAppDomain);
setup.AppDomainInitializerArguments = new string[] { unknownAppPath };
AppDomain testDomain = AppDomain.CreateDomain("test", AppDomain.CurrentDomain.Evidence, setup);
AppDomain.Unload(testDomain);
File.Delete(unknownAppPath);

AppDomain 可以如下初始化

public static void ConfigureAppDomain(string[] args)
{
    string unknownAppPath = args[0];
    AppDomain.CurrentDomain.DoCallBack(delegate()
    {
        //check that the new assembly is signed with the same public key
        Assembly unknownAsm = AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(unknownAppPath));

        //get the new assembly public key
        byte[] unknownKeyBytes = unknownAsm.GetName().GetPublicKey();
        string unknownKeyStr = BitConverter.ToString(unknownKeyBytes);

        //get the current public key
        Assembly asm = Assembly.GetExecutingAssembly();
        AssemblyName aname = asm.GetName();
        byte[] pubKey = aname.GetPublicKey();
        string hexKeyStr = BitConverter.ToString(pubKey);
        if (hexKeyStr == unknownKeyStr)
        {
            //keys match so execute a method
            Type classType = unknownAsm.GetType("namespace.classname");
            classType.InvokeMember("MethodNameToInvoke", BindingFlags.InvokeMethod, null, null, null);
        }
    });
}

关于c# - 将程序集加载到 AppDomain,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10315808/

相关文章:

c# - 你什么时候、为什么要封课?

c# - 在 ASP.NET MVC 中创建 Cookie

c# - 如何从 C# 中的 C++ exe 获取文件版本信息?

从外部线程调用时,.net 单元测试崩溃并显示 "Cannot pass a GCHandle across AppDomains"

c# - 使用 SecurityPermissionFlag.Execution 沙箱化的 AppDomain 有多安全?

c# - 是否可以将图像存储到 pdf417 条码中?

c# - WCF channel 是否有可能在检查状态(单线程)后立即出错?

c# - 如何在C#中继承C++/CLI接口(interface)?

c# - 以框架为目标到底意味着什么,我如何最大限度地提高兼容性?

.net - 混合 MarshalByRefObject 和 Serializable