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.
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.
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.
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.
LoadFrom(String) Loads an assembly given its file name or path.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With