Under a given namespace, I have a set of classes which implement an interface. Let's call it ISomething
. I have another class (let's call it CClass
) which knows about ISomething
but doesn't know about the classes which implement that interface.
I would like that CClass
to look for all the implementation of ISomething
, instantiate an instance of it and execute the method.
Does anybody have an idea on how to do that with C# 3.5?
You could use something like the following and tailor it to your needs.
This code could use some performance enhancements but it's a start.
You can get a list of loaded assemblies by using this:
From there, you can get a list of types in the assembly (assuming public types):
Then you can ask each type whether it supports that interface by finding that interface on the object:
Not sure if there is a more efficient way of doing this with reflection.
A example using Linq:
A working code-sample:
Edit Added a check for a parameterless constructor so that the call to CreateInstance will succeed.
Maybe we should go this way