I have an interface IExample, and a set of classes ClassOne, ClassTwo and ClassThree, all defined in different namespaces. I will possibly remove either of the classes, or add a new one in a new place, at a later stage in development.
Now, I want to find all types that implement IExample at runtime, and instantiate them. (I know on beforehand that no class implementing IExample will ever need any constructor arguments, but I don’t know how to specify that in code, so it’s me – not the compiler – that knows…)
Is this possible? How do I go about to do it?
Update: I’ve now tried several of the approaches suggested, but on all of them, the line Activator.CreateInstance(type), I get a System.MissingMethodException because I “cannot create an instance of an interface.” This is my code:
var tasks = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(t => typeof(IBootstrapperTask).IsAssignableFrom(t))
// This line is where it fails
.Select(t => Activator.CreateInstance(t) as IBootstrapperTask)
.ToArray();
new AutoMapperBootstrapper(tasks).Initialize();
Without the as clause I don’t see any exception, but I’m given an object[], and I need an IBootstrapperTask[] for the constructor on the last line in the excerpt. I’ve tried various ways to cast it, but none seem to work.
This can be done with Reflection. For example
Note: This will only create instances of
IExamplefrom assemblies loaded in the currentAppDomain. This can be different than all assemblies loaded in the current process. However for many types of applications this will be equivalent.