Determine the load context of an assembly

百般思念 提交于 2020-01-01 01:56:08

问题


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

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.


回答1:


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



回答2:


  • reflection-only context: property ReflectionOnly = true
  • no context(dynamic): property IsDynamic = true
  • no context(laod(byteArray): property Location = null
  • default context: either property GlobalAssemblyCache = true or property Location begins with property CodeBase
  • load-from context: anything else assuming you would not load from from code base


来源:https://stackoverflow.com/questions/23408337/determine-the-load-context-of-an-assembly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!