Get a type that implements a common interface by searching for a specific common interface parameter

I would like to create a method that returns a type (or IEnumerable of types) that implements a specific interface that accepts a type parameter, however I want to search for this parameter of a generic type. This is easier to demonstrate as an example:

The signature of the method I want:

 public IEnumerable<Type> GetByInterfaceAndGeneric(Type interfaceWithParam, Type specificTypeParameter)

And if I have the following objects

  public interface IRepository<T> { };
  public class FooRepo : IRepository<Foo> { };
  public class DifferentFooRepo : IRepository<Foo> {};

Then I want:

  var repos = GetByInterfaceAndGeneric(typeof(IRepository<>), typeof(Foo));

and get IEnumerable containing the types FooRepoand DifferentFooRepo.

This is very similar to this question , however, using this example, I would like to search both IRepository<>, and User.

+4
source share
1 answer

You can try the following:

    public static IEnumerable<Type> GetByInterfaceAndGeneric(Type interfaceWithParam, Type specificTypeParameter)
    {
        var query =  
            from x in specificTypeParameter.Assembly.GetTypes()
            where 
            x.GetInterfaces().Any(k => k.Name == interfaceWithParam.Name && 
            k.Namespace == interfaceWithParam.Namespace && 
            k.GenericTypeArguments.Contains(specificTypeParameter))
            select x;
        return query;
    }

;

var types = GetByInterfaceAndGeneric(typeof(IRepository<>), typeof(Foo)).ToList();
+1

Source: https://habr.com/ru/post/1690631/


All Articles