在不同的 AppDomain 中加载具有依赖项的程序集 [英] Load assemblies with dependencies in a different AppDomain

查看:27
本文介绍了在不同的 AppDomain 中加载具有依赖项的程序集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是在 2 个给定文件夹之间进行缺失的依赖关系检查.想象一下以下设置.

My aim is to make a missing dependency check between 2 given folders. Imagine the following setup.

Root\DirA\A.dll

Root\DirA\A.dll

Root\DirB\B.dll

Root\DirB\B.dll

B 依赖于 A.

因此,鉴于这些文件夹,我想创建一个新的 AppDomain,加载 B.dll 并在该新 AppDomain 中自动解析和隔离来自 DirA(A.dll) 的依赖项.

So given these folders, I want to create a new AppDomain, load B.dll and have the dependency from DirA(A.dll) automatically resolved and isolated in that new AppDomain.

隔离是这里的关键,因为当我卸载这个 AppDomain 时,我想再次创建一个可能将 DirA 作为依赖项的新应用程序,但需要它的 DirC 库,因此在 DirC 也依赖于 DirB 的情况下,我想要它抛出异常.

Isolation is key here given that when I unload this AppDomain I want to create a new one with potentially DirA as a dependency again but DirC libraries that require it so in the case that DirC has a dependency on DirB as well I want it to throw an exception.

添加代码示例以帮助更好地描述我的问题.

Adding a code example in case that it helps describe my question better.

AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = @"C:\Root";
setup.ApplicationName = "Isolated Domain"
setup.PrivateBinPath = @"DirA;DirB";
setup.PrivateBinPathProbe = "";//disable search in AppBase..
var domain = AppDomain.CreateDomain(Guid.NewGuid().ToString(),
                                    AppDomain.CurrentDomain.Evidence,
                                    setup,
                                    AppDomain.CurrentDomain.PermissionSet);
//The following statement in theory should pick B.dll's dependency from DirA.
var assembly = domain.Load(AssemblyName.GetAssemblyName(@"C:\Root\DirB\B.dll").Name);
//Do the same in a different domain for C.dll

感谢您对此的任何帮助.

Thanks for any help on that.

推荐答案

这看起来像是 ResolveEventHandler(有关 MSDN 的更多详细信息关于解析未知程序集)

This looks like a job for the ResolveEventHandler (more detail on MSDN regarding resolving unknown assemblies)

所以,你可以写一些类似的东西

So, you can write something like

class MyResolver
{
  public static Assembly MyResolveEventHandler( Object sender, ResolveEventArgs args )
  {
    // confirm args.Name contains A.dll
    String dllName = args.Name.Split({','}, SplitStringOptions.None)[0];
    if (dllName == "A")
    {
      return Assembly.LoadFile(@"C:\Root\DirA\A.dll")
    }
    return null;
  }
}

在您创建的域中,您需要执行以下操作:

and in the domain you created, you'd do a:

domain.AssemblyResolve += new ResolveEventHandler(MyResolver.MyResolveEventHandler);

确保在 B 中引用 A 之前绑定事件.

Make sure you bind the event before you reference A in B.

这篇关于在不同的 AppDomain 中加载具有依赖项的程序集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆