1

I am trying to get a list of all the types in a particular assembly, and then filter that to all types with a constructor that has a particular type as a parameter.

In this case, I'm looking for all constructors that contain 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)))));

I have a number of types with an ILoggerFactory parameter, for example:

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

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

public interface ILoggerFactory { }

However, I'm getting an empty list. I would expect the list to contain MyClass, MyOtherClass, etc. What am I doing wrong with my query?

Rob
  • 26,989
  • 16
  • 82
  • 98
user9993
  • 5,833
  • 11
  • 56
  • 117
  • 6
    `t.IsAssignableFrom`. `t` is the *type with the constructors you're looking for* here. For example, it would be `MyClass` or `MyOtherClass`. You want to write `p.ParameterType.IsAssignableFrom` – Rob Jan 24 '17 at 23:03
  • Write that as an answer I'll mark it as the accepted one @Rob – user9993 Jan 25 '17 at 09:33

0 Answers0