使用特定接口的构造函数参数查找所有类型?

时间:2017-01-24 22:56:57

标签: c# reflection types .net-assembly

我试图获取特定程序集中所有类型的列表,然后使用具有特定类型作为参数的构造函数将其过滤到所有类型。

在这种情况下,我正在寻找包含ILoggerFactory的所有构造函数。

// Get reference to the assembly under test. This is necessary because this code is not contained with the same assembly.
Type type = typeof(Program);
Assembly assembly = type.Assembly;

// Find all types with a constuctor which have a parameter of type ILoggerFactory.
var types = assembly.GetTypes()
    .Where(t => t.GetConstructors()
        .Any(c => c.GetParameters()
            .Any(p => t.IsAssignableFrom(typeof(ILoggerFactory)))));

我有许多带ILoggerFactory参数的类型,例如:

public class MyClass
{
    public MyClass(ILoggerFactory loggerFactory) { }
}

public class MyOtherClass
{
    public MyOtherClass(ILoggerFactory loggerFactory) { }
}

public interface ILoggerFactory { }

但是,我得到一个空列表。我希望该列表包含MyClassMyOtherClass等。我的查询错误了什么?

0 个答案:

没有答案