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

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

问题描述

由于加载大会是有办法(代码),以确定该3负荷上下文它被装入(默认的加载 LoadFrom,既不

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)?

苏珊·库克的选择绑定上下文的文章,也有当一个组件加载到 LoadFrom 。特别是,我的图书馆使用反序列化和遇到 InvalidCastException的当加载到 LoadFrom 上下文。

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.

目前我的图书馆失败很晚(当它执行问题反序列化的代码失败 - 看的我的例子)。我想通过检测其加载到上下文,并抛出一个异常,如果它不加载到默认的加载的上下文,使其无法更早在这种情况下。

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天全站免登陆