Type search in all assemblies

I need to search for specific types in all assemblies on a website or in a Windows application, is there an easy way to do this? Just like the factory controller for ASP.NET MVC looks through all the assemblies for the controllers.

Thank.

+46
reflection c # types
Jan 14 2018-11-11T00:
source share
4 answers

There are two steps to this:

  • AppDomain.CurrentDomain.GetAssemblies() provides you with all the assemblies uploaded to the current application domain.
  • The Assembly class provides the GetTypes() method to retrieve all types inside this particular assembly.

Therefore, your code might look like this:

 foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) { foreach (Type t in a.GetTypes()) { // ... do something with 't' ... } } 

To search for specific types (for example, implementing this interface, inheriting from a common ancestor or something else), you will have to filter the results. In case you need to do this in several places of the application, it is useful to create a helper class that provides various parameters. For example, I used to apply namespace prefix filters, interface implementation filters, and inheritance filters.

See MSDN here and here for detailed documentation.

+75
Jan 14 '11 at 15:09
source share

Simple use of Linq:

 IEnumerable<Type> types = from a in AppDomain.CurrentDomain.GetAssemblies() from t in a.GetTypes() select t; foreach(Type t in types) { ... } 
+25
Jan 15 '11 at 19:09
source share

LINQ solution with checking if the assembly is dynamic:

 /// <summary> /// Looks in all loaded assemblies for the given type. /// </summary> /// <param name="fullName"> /// The full name of the type. /// </param> /// <returns> /// The <see cref="Type"/> found; null if not found. /// </returns> private static Type FindType(string fullName) { return AppDomain.CurrentDomain.GetAssemblies() .Where(a => !a.IsDynamic) .SelectMany(a => a.GetTypes()) .FirstOrDefault(t => t.FullName.Equals(fullName)); } 
+19
Dec 31 '14 at 7:12
source share

Most often you are only interested in nodes that are visible from the outside. To do this, you need to call GetExportedTypes () . But you can also throw a ReflectionTypeLoadException . The following code will take care of these situations.

 public static IEnumerable<Type> FindTypes(Func<Type, bool> predicate) { if (predicate == null) throw new ArgumentNullException(nameof(predicate)); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (!assembly.IsDynamic) { Type[] exportedTypes = null; try { exportedTypes = assembly.GetExportedTypes(); } catch (ReflectionTypeLoadException e) { exportedTypes = e.Types; } if (exportedTypes != null) { foreach (var type in exportedTypes) { if (predicate(type)) yield return type; } } } } } 
+3
Mar 04 '16 at 14:08
source share



All Articles