Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Reflection: Get *all* active assemblies in a solution?

Tags:

c#

reflection

Here's my problem:

I have 2 projects - one 'common' projects with acts like a library with all kinds of support code, and the actual program that uses said project in many of its calls. We'll call these projects "Common" and "Program". They are both in the same solution.

Within "Common", I have a class for common reflection tasks, like creating an instance. If I call GetExecutingAssembly, it gets all the "Common" Types, however when I use GetEntryAssembly I get the "Program" types.

While I certainly could edit the code to work with 2 sets of asm, I'm afraid of a situation where there are more than just 2 projects in the solution - lets say 5 (don't know why, but lets just go there for now), and I'm afraid that calling GetExecutingAssembly and GetEntryAssembly will not get all the Types in the entire program.

Is there something else that i can do to get all the Types in a solution?

like image 623
cyberconte Avatar asked May 12 '09 05:05

cyberconte


2 Answers

Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); 

This will get all of the loaded assemblies in the current AppDomain.

As noted in the comments, it's possible to spawn multiple AppDomains, in which case each can have its own assemblies. The immediate advantage to doing so is that you can unload Assemblies by unloading the containing AppDomain.

like image 70
bsneeze Avatar answered Sep 23 '22 12:09

bsneeze


This is a really old question, but for future reference here's a complete implementation:

    public static IEnumerable<Assembly> GetAssemblies()     {         var list = new List<string>();         var stack = new Stack<Assembly>();          stack.Push(Assembly.GetEntryAssembly());          do         {             var asm = stack.Pop();              yield return asm;              foreach (var reference in asm.GetReferencedAssemblies())                 if (!list.Contains(reference.FullName))                 {                     stack.Push(Assembly.Load(reference));                     list.Add(reference.FullName);                 }          }         while (stack.Count > 0);      } 
like image 35
3Dave Avatar answered Sep 23 '22 12:09

3Dave