Ricardo Alves
Ricardo Alves

Reputation: 1131

Reflection to get if class has an interface that "implements" another interface

I'm currently trying to achieve the following:

I have a interface this interface:

public interface IRepository<TEntity>
{
   //Some Methods
}

Then I have another interface that extends the one above:

public interface IAttractionRepository : IRepository<Attraction>
{
   //More methods
}

Finally, I have an implementation (that also implements other interfaces):

public class AttractionRepository : ISomethingElse, IAnotherSomethingElse, IAttractionRepository
{
  //Implementations and methods
}

What I am trying to achieve is: Provided type AttractionRepository, I want to search it's interfaces and get which one is extending the intercface IRepository.

My code is as follows:

Type[] interfaces = typeof(AttractionRepository).GetInterfaces(); //I get three interfaces here, which is fine.
Type iface = null;

foreach (Type t in interfaces) //Iterate through all interfaces
    foreach(Type t1 in t.GetInterfaces()) //For each of the interfaces an interface is extending, I want to know if there's any interface that is "IRepository<Attraction>"
        if (t1.IsSubclassOf(typeof(IRepository<>).MakeGenericType(typeof(Attraction)))) //Always false
            iface = t;

I have tried several other solutions but with no success.

Upvotes: 1

Views: 53

Answers (1)

James
James

Reputation: 3928

Something like this is very handy for this situation:

/// <summary>
/// Returns whether or not the specified class or interface type implements the specified interface.
/// </summary>
/// <param name="implementor">The class or interface that might implement the interface.</param>
/// <param name="interfaceType">The interface to look for.</param>
/// <returns><b>true</b> if the interface is supported, <b>false</b> if it is not.</returns>
public static bool ImplementsInterface(this Type implementor, Type interfaceType)
{
    if (interfaceType.IsGenericTypeDefinition)
    {
        return (implementor.IsGenericType && implementor.GetGenericTypeDefinition() == interfaceType) ||
            (implementor.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType));
    }
    else return interfaceType.IsAssignableFrom(implementor);
}

The problem is that there isn't a built-in function for this, due to the fact that the interface you're looking for is a generic interface.

In your specific case, you'd use it something like this:

Type implementingInterface = typeof(AttractionRepository).GetInterfaces().Where(i => i.ImplementsInterface(typeof(IRepository<>))).FirstOrDefault();

Upvotes: 1

Related Questions