简体   繁体   English

如何在程序集中搜索实现所需通用接口的类型

[英]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. 立即窗口返回2种类型,在调试器下运行的测试代码仅返回非泛型实现。

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. 将加载的程序集与Assembly.GetExecutingAssembly()进行比较时,程序集不相等。 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. 移动使用AppDomain.CurrentDomain.GetAssemblies()解决了这个问题,因为我正在加载已由应用程序加载的程序集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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