Skip to content

Reflection & Assemblies

Mehdi Hadeli edited this page Jan 9, 2023 · 26 revisions

One example for this is Hypothesist assemblies which is load with its dependent assemblies doesn't load, and we get ReflectionTypeLoadException because it can't find correspond dependent Assembly version MassTransit. It is better to use GetReferencedAssemblies

AppDomain.CurrentDomain.GetAssemblies().ToArray();

Assemblies load by AppDomain based on their code path and their code usage. Assembly will add to AppDomain dynamically by Jit when visit one of assembly class method.

We could load all references assembly with using this helper function, and load all references assemblies explicitly with Assembly.Load(reference):

ReflectionUtilities.GetAllReferencedAssemblies(Assembly.GetCallingAssembly()).ToArray();

public static IEnumerable<Assembly> GetAllReferencedAssemblies(Assembly? rootAssembly)
{
	var list = new HashSet<string>();
	var stack = new Stack<Assembly?>();

	var root = rootAssembly ?? Assembly.GetEntryAssembly();
	stack.Push(root);

	do
	{
		var asm = stack.Pop();

		if (asm == null)
			break;

		yield return asm;

		foreach (var reference in asm.GetReferencedAssemblies())
		{
			if (!list.Contains(reference.FullName))
			{
				// loading assemblies explicitly, because assemblies are loaded lazily
				stack.Push(Assembly.Load(reference));
				list.Add(reference.FullName);
			}
		}
	}
	while (stack.Count > 0);
}
Clone this wiki locally