如何在AssemblyResolve中使用AppDomain.CreateDomain?

时间:2012-03-15 14:21:56

标签: c# oop c#-4.0 applicationdomain

我想通过使用内存从WCF加载程序集。一切都运转良好的时候:

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

但我想使用AppDomain.CreateDomain,而不是当前域:

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);
}

我有两个类库,ClassLibrary1和ClassLibrary2使用如下:

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依赖于ClassLibrary1。所以我使用的是assemblyresolver。但我在 ApplicationHost.Load(二进制);

上收到错误
  

错误:无法加载文件或程序集“ClassLibrary1,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null”或其中一个依赖项。系统找不到指定的文件。

此外,它还没有成功解决问题。我的光标不会转到Assemblyresolver方法。如何将AppDomain.CreateDomain与resolve方法一起使用?

1 个答案:

答案 0 :(得分:0)

我个人不喜欢从字节数组加载程序集。我认为最好将程序集保存到临时文件夹,然后从该文件夹加载它们。看一下这篇文章: Application Domains is hard…