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.
Use Type. GetType to get the Type objects from an assembly that is already loaded.
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.
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.
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.
There are two steps to achieve this:
AppDomain.CurrentDomain.GetAssemblies()
gives you all assemblies loaded in the current application domain.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With