确定程序集的加载上下文 [英] Determine the load context of an assembly

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

问题描述

给定一个加载的 Assembly 有没有办法(在代码中)确定它被加载到 3 个加载上下文中的哪个(默认 LoadLoadFrom、 还是 都不是)?

Given a loaded Assembly is there a way (in code) to determine which of the 3 load contexts it was loaded into (default Load, LoadFrom, or Neither)?

Suzanne Cook 的选择绑定上下文" 文章,将程序集加载到 LoadFrom 时会出现一些缺点.特别是,我的库使用反序列化并在加载到 LoadFrom 上下文时遇到 InvalidCastException.

In Suzanne Cook's "Choosing a Binding Context" article, there are some disadvantages that occur when an assembly is loaded into the LoadFrom. In particular, my library uses deserialization and encounters an InvalidCastException when loaded into the LoadFrom context.

目前我的库很晚才失败(它在执行有问题的反序列化代码时失败了——参见 我的例子).我想通过检测它加载到的上下文并在未加载到默认 Load 上下文时抛出异常,使其在这些情况下更早地失败.

Currently my library fails very late (it fails when it executes the problematic deserialization code--see my example). I'd like to make it fail much earlier in these circumstances by detecting the context it is loaded into and throwing an exception if it is not loaded into the default Load context.

推荐答案

您可以测试程序集的行为,而不是识别程序集的上下文.例如,对于序列化,序列化程序将调用 Assembly.Load 并且该程序集必须匹配正在序列化的对象的程序集.可以通过检查代码库来测试匹配.

Instead of identifying the context of the assembly, you could test the behavior of it. For example, for serializing, the serializer will call Assembly.Load and that assembly must match the assembly of the object being serialized. A match can be tested for by checking the CodeBase.

private static bool DoesAssemblyMatchLoad(Assembly assemblyToTest)
{
    try
    {
        var loadedAssembly = Assembly.Load(assemblyToTest.FullName);
        return assemblyToTest.CodeBase == loadedAssembly.CodeBase;
    }
    catch (FileNotFoundException)
    {
        return false;
    }
}

这篇关于确定程序集的加载上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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