Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with an interface dynamically loaded from an assembly and invoke its members

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.

like image 261
Mats Avatar asked Dec 27 '25 14:12

Mats


1 Answers

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.

like image 180
Matt Hamilton Avatar answered Dec 31 '25 19:12

Matt Hamilton