mardi 24 janvier 2017

Finding all types with a constructor parameter of a particular interface?

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?





Aucun commentaire:

Enregistrer un commentaire