mardi 16 avril 2019

How to search assemblies for types that implement desired generic interface

I am searching through assemblies to identify any classes that implement a desired generic interface so I can dynamically instantiate an instance. This is the code I'm using:

var types = assembly.GetTypes();
var assemblyFormatters = types.Where(type => type.GetInterfaces().Any(i => 
   i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IInterface<>)));

The code works for a standard class:

public class Implementation : IInterface<object>

but not for a generic class:

public class GenericImplementation<T> : IInterface<T>

Event stranger, the code works successfully when run in the intermediate window, but not when run within a unit test framework. The immediate window returns 2 types, the test code run under the debugger returns only the non generic implementation.

I would expect both types to be returned by the code





Aucun commentaire:

Enregistrer un commentaire