I have got some code to load an assembly and get all types, which implement a certain interface, like this (assume asm is a valid and loaded assembly).
var results = from type in asm.GetTypes()
where typeof(IServiceJob).IsAssignableFrom(type)
select type;
Now I'm stuck: I need to create instances of these objects and invoke methods and properties on the object. And I need to store the references to the created objects in an array for later usage.
Oh wow - I only blogged about this a few days ago. Here's my method to return instances of all the types that implement a given interface:
private static IEnumerable<T> InstancesOf<T>() where T : class
{
var type = typeof(T);
return from t in type.Assembly.GetExportedTypes()
where t.IsClass
&& type.IsAssignableFrom(t)
&& t.GetConstructor(new Type[0]) != null
select (T)Activator.CreateInstance(t);
}
If you refactor this to accept an assembly parameter rather than using the interface's assembly, it becomes flexible enough to suit your need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With