How to work with an interface dynamically loaded from an assembly and call its elements

I have code to load an assembly and get all types that implement a specific interface, for example (suppose that 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 instantiate these objects and call the methods and properties of the object. And I need to save references to created objects in an array for later use.

+3
source share
2 answers

Oh wow - I only wrote about this a few days ago. Here, my method returns instances of all types that implement this 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);
}

, , , , .

+11

Activator.CreateInstance: -

IServiceJob x = Activator.CreateInstance(type);

, : -

IServiceJob[] results = (from type in asm.GetTypes()
  where typeof(IServiceJob).IsAssignableFrom(type)
  select (IServiceJob)Activator.CreateInstance(type)).ToArray();

( var IServiceJob [], , ).

+1

Source: https://habr.com/ru/post/1699407/


All Articles