'Prevent Assembly.GetTypes() from loading dependencies

I have assembly A referencing assembly B. They are located in the same directory.

Type[] types = null;
try
{
  Assembly a = Assembly.Load("A.dll");
  types = a.GetTypes(); // loads B implicitly.
}
catch(ReflectionTypeLoadException ex)
{
  types = ex.Types.Where(x=>x!=null);
}

How do I prevent B from being loaded? I want GetTypes() to run as if B wasn't available and to return only available types and null's for not available so I could execute ex.Types.where(x=>x!=null);

I want to use the trick from How to prevent ReflectionTypeLoadException when calling Assembly.GetTypes()

This way I can get only types that don't depend on B and work with them.

Update:

I loaded A in the reflection as well as in the normal context. I used the reflection context A for calling GetTypes(). After getting types from the reflection context assembly, I had another problem. When I called Type.GetCustomAttributes(), I received the following exception

It is illegal to reflect on the custom attributes of a Type loaded via ReflectionOnlyGetType (see Assembly.ReflectionOnly) -- use CustomAttributeData instead.

I solved it by getting the same type from the normal context assembly.

//... code omited for brevity
Type reflectionType = reflectionAssembly.GetTypes()[0];
//... code omited for brevity
Type goodType = normalAssembly.GetType(reflectionType.FullName);

This way I prevented loading of B and used types from A independent from B.



Solution 1:[1]

It's 2022, and .NET 6 is here, so the solution mentioned above is officially obsolete.

Here is a new solution: https://github.com/dotnet/corefxlab/blob/master/docs/specs/typeloader.md

Apparently, this is an archived experimental repository, so you have to embed the code into your project manually. Take note of the license.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sergey