Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine the load context of an assembly

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.

like image 653
Matt Smith Avatar asked May 01 '14 13:05

Matt Smith


People also ask

What is load context?

Conceptually, a load context creates a scope for loading, resolving, and potentially unloading a set of assemblies. The AssemblyLoadContext exists primarily to provide assembly loading isolation. It allows multiple versions of the same assembly to be loaded within a single process.

What is assembly context?

These connections, called Assembly Contexts, allow part of the assembly to be derived into the external files, so the external file can be developed independently from the main assembly. Updates at the assembly level can be pulled into the xref by synchronizing the assembly context.

What is load in assembly?

A load operation copies data from main memory into a register. A store operation copies data from a register into main memory . When a word (4 bytes) is loaded or stored the memory address must be a multiple of four. This is called an alignment restriction.

What is the method to load assembly given its file name and its path?

LoadFrom(String) Loads an assembly given its file name or path.


1 Answers

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;
    }
}
like image 141
Josh Avatar answered Oct 13 '22 12:10

Josh