vendredi 13 novembre 2015

Find all types implementing a certain generic interface with specific T type

I have several classes inheriting from abstract class BrowsingGoal. Some of these implement an interface called ICanHandleIntent<TPageIntent> where TPageIntent: PageIntent.

To give a concrete example:

public class Authenticate : BrowsingGoal, ICanHandleIntent<AuthenticationNeededIntent>
{
    ...
}

Now I would like to scan the CurrentDomain's assemblies for all types implementing the ICanHandleIntent with the AuthenticationNeededIntent. This is what I have so far but it doesn't seem to find anything:

protected BrowsingGoal FindNextGoal(PageIntent intent)
{
    // Find a goal that implements an ICanHandleIntent<specific PageIntent>
    var goalHandler = AppDomain.CurrentDomain
        .GetAssemblies()
        .SelectMany(assembly => assembly.GetTypes())
        .FirstOrDefault(t => t.IsAssignableFrom((typeof (BrowsingGoal))) &&
                                t.GetInterfaces().Any(x =>
                                    x.IsGenericType &&
                                    x.IsAssignableFrom(typeof (ICanHandleIntent<>)) &&
                                    x.GetGenericTypeDefinition() == intent.GetType()));

    if (goalHandler != null)
        return Activator.CreateInstance(goalHandler) as BrowsingGoal;
}

Some help would be very appreciated!





Aucun commentaire:

Enregistrer un commentaire