Jon
Jon

Reputation: 40062

Using reflection to find constructors that have interface parameters

I am loading up all assemblies in my app domain and then trying to find those of a certain base type and all also whose constructors have a interface as a constructor argument. I've got the below code but can't work out how you tell it to find interface parameters.

var assembliesWithPluginBaseInThem = AppDomain.CurrentDomain.GetAssemblies()
    .Where(x=>x.GetTypes().Where(y=>y.BaseType== typeof(PluginBase) &&
     y.GetConstructor(new Type[]{typeof(interface)})

Upvotes: 2

Views: 1982

Answers (3)

Nikola Radosavljević
Nikola Radosavljević

Reputation: 6911

How about something like this:

var assembliesWithPluginBaseInThem = AppDomain.CurrentDomain.GetAssemblies()
    .Where(x =>
        x.GetTypes().Any(y =>
            typeof(PluginBase).IsAssignableFrom(y) &&
            y.GetConstructors().Any(z =>
                z.GetParameters().Count() == 1 && // or maybe you don't want exactly 1 param?
                z.GetParameters().All(a => a.ParameterType.IsInterface)
            )
        )
    );

Upvotes: 3

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

to check is a class in a subclass of a certain type I would suggest you to use

yourClass.IsSubclassOf(typeof(parentClass))

so it should look like the below:

var assembliesWithPluginBaseInThem = AppDomain.CurrentDomain.GetAssemblies()
    .Where(x=>x.GetTypes().Where(y=>y.IsSubclassOf(typeof(PluginBase)) &&
     y.GetConstructor.Any(c => c.GetParameters()
                              .Any(p => p.ParameterType.IsInterface)

Upvotes: 1

Thomas Levesque
Thomas Levesque

Reputation: 292635

var types =
    from a in AppDomain.CurrentDomain.GetAssemblies()
    from t in a.GetTypes()
    where t.GetConstructors()
                 .Any(c => c.GetParameters()
                              .Any(p => p.ParameterType.IsInterface))
    select t;

Upvotes: 3

Related Questions