8

我正在尝试通过挂钩AppDomain.AssemblyResolveAppDomain.ReflectionOnlyAssemblyResolve事件来加载一些模块。当我让前者工作时,我在后者上失败了。我把我的问题归结为这个小程序:

public static class AssemblyLoader
{
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += 
            ReflectionOnlyAssemblyResolve;

        // fails with FileNotFoundException
        Assembly.ReflectionOnlyLoad("Foo");
    }

    public static Assembly ReflectionOnlyAssemblyResolve(object sender, 
        ResolveEventArgs args)
    {
        Trace.TraceInformation(
            "Failed resolving Assembly {0} for reflection", args.Name);

        return null;
    }
}

FileNotFoundException尝试运行此程序失败Assembly.ReflectionOnlyLoad,但它不调用 ReflectionOnlyAssemblyResolve 处理程序。我很困惑。

有谁知道这可能是什么根本原因以及如何让它发挥作用?

谢谢!

4

3 回答 3

8

看起来 ReflectionOnlyAssemblyResolve 事件仅用于解决依赖关系,而不是顶级程序集,如下所示:

http://codeidol.com/csharp/net-framework/Assemblies,-Loading,-and-Deployment/Assembly-Loading/

和这里:

http://blogs.msdn.com/junfeng/archive/2004/08/24/219691.aspx

于 2009-02-20T16:17:05.090 回答
1

扩展 casperOne 的答案。

如果要拦截直接的 Assembly Resolve 事件,则需要挂钩 AppDomain.AssemblyResolve 事件。虽然这是一个全局钩子,但它本身并不适合您的场景。但是,如果您的应用程序是单线程的,您可以进行短期连接以拦截特定的解析事件。

static void LoadWithIntercept(string assemblyName) {
  var domain = AppDomain.CurrentDomain;
  domain.AssemblyResolve += MyInterceptMethod;
  try {
    Assembly.ReflectionOnlyLoad(assemblyName);
  } finally {
    domain.AssemblyResolve -= MyInterceptMethod;
  }
}

private static Assembly MyInterceptMethod(object sender, ResolveEventArgs e) {
 // do custom code here 
}
于 2009-02-20T17:06:08.797 回答
0

您可以通过在程序集上调用 ExportedTypes 来强制它,如下所示:

var dummy = asm.ExportedTypes;

因此,如果您想以递归方式加载具有所有引用的程序集:

 private void _forceAssemblyResolve(Assembly asm) { var dummy = asm.ExportedTypes; }

 var result= Assembly.ReflectionOnlyLoad("Foo");
 _forceAssemblyResolve(result);

public static Assembly ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
    var childAssembly = _resolve(args);
    _forceAssemblyResolve(childAssembly);
}
于 2018-09-07T11:08:03.843 回答