3

I'm building a command extension for the UML Sequence Diagram in VS2010, and need a list of types that implement a particular interface in the current solution. How do you access type and assembly information from an extension? So far all of my attempts have just listed assemblies loaded in the original extension project, not the one that VS is currently editing.

shader
  • 801
  • 1
  • 7
  • 25

1 Answers1

5

Here's the solution I finally arrived at, using linq to simplify the search:

DTE dte = (DTE)ServiceProvider.GetService(typeof(DTE));
var types = from Project project in dte.Solution.Projects
            from Reference reference in (References)project.Object.References
            where reference.Type == prjReferenceType.prjReferenceTypeAssembly
            from t in Assembly.LoadFile(reference.Path).GetTypes()
            where t != typeof(IInterface) && typeof(IInterface).IsAssignableFrom(t)
            select t;

This block searches through all projects contained in the currently open solution, gets all of their references, loads the ones which are assemblies, and searches them for types that implement the interface.

shader
  • 801
  • 1
  • 7
  • 25
  • 1
    Note that you are loading all these assemblies into devenv.exe with Reflection, meaning they are consuming memory, and you cannot free this memory until devenv.exe dies. (This might not matter to you, just saying... an alternative that avoids this is could be to use MonoCecil instead of Reflection) – Omer Raviv Jul 13 '11 at 15:53
  • Using memory isn't that big of an issue, since this is a design-time operation, but I am still having some trouble with this solution. Sometimes it won't load all of the dependencies of the assemblies, and the GetTypes() call throws a ReflectionTypeLoadException. I'm not sure how to ensure that the dependencies are loaded, or at least available before calling GetTypes(), so it might be best if there was another way to do this. – shader Jul 13 '11 at 18:35