将程序集加载到AppDomain中

4

if i use

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内得到了该类的实例。

我需要整个过程。

就像这个问题中提供的另一个示例:创建实例的另一个示例。

将DLL加载到单独的AppDomain中


你看过 http://msdn.microsoft.com/en-us/library/25y1ya39.aspx 吗? - rt2800
1
也许这个答案可以帮到你?https://dev59.com/GnVC5IYBdhLWcg3wpS7g#225355 - Jan-Peter Vos
1个回答

3
最基本的多域名场景是:
static void Main()
{
    AppDomain newDomain = AppDomain.CreateDomain("New Domain");
    newDomain.ExecuteAssembly("file.exe");
    AppDomain.Unload(newDomain);
}

在一个单独的域上调用ExecuteAssembly很方便,但不提供与该域本身交互的能力。它还需要目标程序集是可执行文件,并强制调用者使用单个入口点。为了增加一些灵活性,您还可以将字符串或args传递给.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);
        }
    });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接