Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Types in All Assemblies

I need to look for specific types in all assemblies in a web site or windows app, is there an easy way to do this? Like how the controller factory for ASP.NET MVC looks across all assemblies for controllers.

Thanks.

like image 942
Brian Mains Avatar asked Jan 14 '11 14:01

Brian Mains


People also ask

How do you get type objects from assemblies?

Use Type. GetType to get the Type objects from an assembly that is already loaded.

Which of the given methods is used in C# to get the details about information types in an assembly during runtime?

Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System. Reflection namespace. The System.

How do I get assembly from namespace?

In order to get the namespaces for an assembly you must use several reflection features. Firstly, you obtain an Assembly instance, either by getting the currently executing assembly or by loading an assembly using the static methods of the Assembly class.

What is AC assembly?

It is basically a compiled code that can be executed by the CLR. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An Assembly can be a DLL or exe depending upon the project that we choose.


1 Answers

There are two steps to achieve this:

  • The AppDomain.CurrentDomain.GetAssemblies() gives you all assemblies loaded in the current application domain.
  • The Assembly class provides a GetTypes() method to retrieve all types within that particular assembly.

Hence your code might look like this:

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

To look for specific types (e.g. implementing a given interface, inheriting from a common ancestor or whatever) you'll have to filter-out the results. In case you need to do that on multiple places in your application it's a good idea to build a helper class providing different options. For example, I've commonly applied namespace prefix filters, interface implementation filters, and inheritance filters.

For detailed documentation have a look into MSDN here and here.

like image 154
Ondrej Tucny Avatar answered Nov 06 '22 07:11

Ondrej Tucny