How do I put all the types matching a particular C# interface in an IDictionary?
- by Kevin Brassen
I have a number of classes all in the same interface, all in the same assembly, all conforming to the same generic interface:
public class AppleFactory : IFactory<Apple> { ... }
public class BananaFactory : IFactory<Banana> { ... }
// ...
It's safe to assume that if we have an IFactory<T> for a particular T that it's the only one of that kind. (That is, there aren't two things that implement IFactory<Apple>.)
I'd like to use reflection to get all these types, and then store them all in an IDictionary, where the key is typeof(T) and the value is the corresponding IFactory<T>. I imagine eventually we would wind up with something like this:
_map = new Dictionary<Type, object>();
foreach(Type t in [...]) {
object factoryForType = System.Reflection.[???](t);
_map[t] = factoryForType;
}
What's the best way to do that? I'm having trouble seeing how I'd do that with the System.Reflection interfaces.