How to get all implementations of an interface through reflection in C#
Do you mean all interfaces a Type implements?
Like this:
ObjX foo = new ObjX();
Type tFoo = foo.GetType();
Type[] tFooInterfaces = tFoo.GetInterfaces();
foreach(Type tInterface in tFooInterfaces)
{
// do something with it
}
Hope tha helpts.
Have a look at Assembly.GetTypes() method. It returns all the types that can be found in an assembly. All you have to do is to iterate through every returned type and check if it implements neccesary interface.
On of the way to do so is using Type.IsAssignableFrom method.
Here is the example. myInterface is the interface, implementations of which you are searching for.
Assembly myAssembly;
Type myInterface;
foreach (Type type in myAssembly.GetTypes())
{
if (myInterface.IsAssignableFrom(type))
Console.WriteLine(type.FullName);
}
I do beleive that it is not a very efficient way to solve your problem, but at least, it is a good place to start.
Assembly assembly = Assembly.GetExecutingAssembly();
List<Type> types = assembly.GetTypes();
List<Type> childTypes = new List<Type>();
foreach (Type type in Types) {
foreach (Type interfaceType in type.GetInterfaces()) {
if (interfaceType.Equals(typeof([yourinterfacetype)) {
childTypes.Add(type)
break;
}
}
}
Maybe something like that....
The anwer is this; it searches through the entire application domain -- that is, every assembly currently loaded by your application.
/// <summary>
/// Returns all types in the current AppDomain implementing the interface or inheriting the type.
/// </summary>
public static IEnumerable<Type> TypesImplementingInterface(Type desiredType)
{
return AppDomain
.CurrentDomain
.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes())
.Where(type => desiredType.IsAssignableFrom(type));
}
It is used like this;
var disposableTypes = TypesImplementingInterface(typeof(IDisposable));
You may also want this function to find actual concrete types -- ie, filtering out abstracts, interfaces, and generic type definitions.
public static bool IsRealClass(Type testType)
{
return testType.IsAbstract == false
&& testType.IsGenericTypeDefinition == false
&& testType.IsInterface == false;
}
You have to loop over all assemblies that you are interested in. From the assembly you can get all the types it defines. Note that when you do AppDomain.CurrentDomain.Assemblies you only get the assemblies that are loaded. Assemblies are not loaded until they are needed, so that means that you have to explicitly load the assemblies before you start searching.