How do I use AppDomain.CreateDomain with AssemblyR

2020-07-22 09:52发布

问题:

I want to load my assemblies from WCF by using memory. Everything is working good WHEN:

AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
Assembly[] assBefore = AppDomain.CurrentDomain.GetAssemblies();
foreach (byte[] binary in deCompressBinaries)
    loadedAssembly = AppDomain.CurrentDomain.Load(binary);

But I want to use AppDomain.CreateDomain, not the current domain:

protected void LoadApplication()
{
    this.ApplicationHost = AppDomain.CreateDomain("TestService", null, new AppDomainSetup
    {
        ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
    });

    ApplicationHost.AssemblyResolve += new ResolveEventHandler(OnAssemblyResolve);
    foreach (AssemblyName asmbly in System.Reflection.Assembly.GetExecutingAssembly().GetReferencedAssemblies())
    {
        ApplicationHost.Load(asmbly);
    }
    List<byte[]> deCompressBinaries = new List<byte[]>();
    foreach (var item in AppPackage.Item.AssemblyPackage)
        deCompressBinaries.Add(item.Buffer);
    var decompressvalues =  DeCompress(deCompressBinaries);
    deCompressBinaries.Clear();
    deCompressBinaries = decompressvalues.ToList();

    foreach (byte[] binary in deCompressBinaries)
        ApplicationHost.Load(binary);

    Assembly[] assAfter = AppDomain.CurrentDomain.GetAssemblies();
}

Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
{
    return Assembly.Load(args.Name);
}

I have two class libraries, ClassLibrary1 and ClassLibrary2 using the below:

namespace ClassLibrary2
{
    public class Class1 : MarshalByRefObject
    {
        public Class1()
        {

        }

        public int GetSum(int a , int b)
        {
            try
            {
                ClassLibrary1.Class1 ctx = new ClassLibrary1.Class1();
                return ctx.Sum(a, b);
            }
            catch
            {
                return -1;
            }
        }

        public int GetMultiply(int a, int b)
        {
            return a * b;
        }
    }
}

Classlibrary2 depends on ClassLibrary1. So I am using assemblyresolver. But I get an error on ApplicationHost.Load(binary);:

Error: Could not load file or assembly 'ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

Also it is NOT FIRING ASSEMBLYRESOLVER. My cursor is not going to the Assemblyresolver method. How do I use AppDomain.CreateDomain with the resolve method?

回答1:

I personally don't like loading assemblies from a byte array. I think it is better to save your assemblies to a temporary folder and then load them from that folder. Take a look at this article: Application Domains is hard….