简体   繁体   中英

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

Turns out it is an issue with assemblies. I was loading in the assemblies using:

var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
foreach (var assembly in Directory.GetFiles(path, "*.dll"))
{
    Assembly.LoadFile(assembly);
}

When comparing the loaded assembly with Assembly.GetExecutingAssembly(), the assemblies are not equal. Since types have references to their respective assemblies, the types were therefore not equal. Moving to use AppDomain.CurrentDomain.GetAssemblies() solved the problem, as I was loading assemblies already loaded by the application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM