Question

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.

Était-ce utile?

La solution

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

Autres conseils

  • reflection-only context: Assembly.ReflectionOnly == true

  • no context (dynamic): Assembly.IsDynamic == true

  • no context (Load(byte[])): Assembly.Location == null

  • default context: either Assembly.GlobalAssemblyCache == true or Assembly.Location begins with property CodeBase

  • load-from context: anything else assuming you would not load from from code base

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top