Skip to content

Reflection & Assemblies

Mehdi Hadeli edited this page Jan 9, 2023 · 26 revisions
AppDomain.CurrentDomain.GetAssemblies().ToArray();

Assemblies load by AppDomain based on their dependency graph 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