2

I need to get all the objects in my application that implement a given interface. How can i achieve this?

Thank you

To clarify I'm looking for instances NOT for Types.


To clarify again, i guess ill need to do something evil like get all the threads associated with my AppDomain and walk their stacks.

Again- my boss's idea... i thought of doing using IOC or AOP....

AK_
  • 7,981
  • 7
  • 46
  • 78

4 Answers4

3

This will search all the loaded assemblies.

AppDomain myDomain = AppDomain.CurrentDomain;
Assembly[] loadedAssemblies = MyDomain.GetAssemblies();
foreach(Assembly assembly in loadedAssemblies)
{
    Type[] types = assembly.GetTypes();
    foreach (Type type in types)
    {
        if (type.GetInterface(interface name) != null)
            Console.WriteLine(type.Name);
    }
}
Itay Karo
  • 17,924
  • 4
  • 40
  • 58
  • This is just finding the types, not the instances. He needs a IoC container of some sort. With that said, I did find your code useful :) – N_tro_P Mar 22 '16 at 13:55
2

This cannot be done.

To find an object, you need a reference to it. If you do not have a reference to it, but want to "find" it, this is not possible.

Pieter van Ginkel
  • 29,160
  • 8
  • 71
  • 111
1

One way to do it would be to use MEF and it would probably perform better than using standard reflection.

http://mef.codeplex.com/

You basically add an attribute to all your interface implementations and MEF can then scan your assemblies (and any others in any folders you tell it to scan) for the implementations.

BenCr
  • 5,991
  • 5
  • 44
  • 68
0

So you want to find all instances that implement a specific interface - not the classes, the actual objects. You need to somehow enumerate over instances of objects. I am not aware of a way to do that.

If you could, however, create some sort of common ancestor for all the relevant objects that you have (something like your own Object class) then you can add a static enumeration of all the instances that were created by registering them in the constructor. You can then simply run over them and check each instance to see if it implements the interface. The problem with this approach is, of course, that these instances will never be garbage collected, even when you are done using them because they always have a reference pointing to them.

This leads me to the concolusion that there probably isn't a "built in" way to enumerate over instances of a class or interface, or even to enumerate over all the instances in the memory because having any such enumeration object means that these instances can never be garbage collected even when you no longer have a reference to them, because they can still be "referenced". This idea condradicts the whole point in managed code... So unless you find your own way to enumerate the instances, I don't think you will be able to do that.

hope that helps :-)

Kobi Hari
  • 1,259
  • 1
  • 10
  • 25