tags:

views:

546

answers:

3

We need to get all the instances of objects that implement a given interface - can we do that, and if so how?

+1  A: 

I don't believe there is a way... You would have to either be able to walk the Heap, and examine every object there, or walk the stack of every active thread in the application process space, examining every stack reference variable on every thread...

The other way, (I am guessing you can't do) is intercept all Object creation activities (using a container approach) and keep a list of all objects in your application...

Charles Bretana
+3  A: 

Here's some pseudocode that looks remarkably like C# and may even compile and return what you need. If nothing else, it will point you in the correct direction:

        public static IEnumerable<T> GetInstancesOfImplementingTypes<T>()
        {
            AppDomain app = AppDomain.CurrentDomain;
            Assembly[] ass = app.GetAssemblies();
            Type[] types;
            Type targetType = typeof(T);

            foreach (Assembly a in ass)
            {
                types = a.GetTypes();
                foreach (Type t in types)
                {
                    if (t.IsInterface) continue;
                    if (t.IsAbstract) continue;
                    foreach (Type iface in t.GetInterfaces())
                    {
                        if (!iface.Equals(targetType)) continue;
                        yield return Activator.CreateInstance(t);
                        break;
                    }
                }
            }
        }

Now, if you're talking about walking the heap and returning previously instantiated instances of all objects that implement a particular type, good luck on that. I'd suggest you post the reason why you think you need to do that, and people will probably suggest better ways of going about it.

Will
Yeah, I want to get previously-instantiated instances. It's because we load modules that store their settings using objects that implement the same interface, but there doesn't seem to be any other way to get the setting instances out.
Simon
+2  A: 

All instances of an Object, or all Types?

Getting all instances of an Object would be pretty close to impossible, and would involve non-public information about the scan through management memory.

Getting all types that implement a given interface is doable --- within a given domain. (ie, you can find all type defined within an assembly that implement a particular interface)

  • Load the Assembly
  • Iterate through it's types (call asm.GetTypes())
  • Check typeof(IMyInterface).IsAssignibleFrom(testType)
James Curran
All instances of an object.
Simon