Wednesday, July 30, 2008

Recursively Searching for Classes of Specified Type from an Assembly or Type

Sometimes I find myself implementing a plugin architecture and I need to find a list of classes in an assembly that qualify as plugins for a given project.  I wrote the following class to help me do this:

public static class TypeFinder
{
    public static List<Type> GetTypesFromAssembly(Assembly assembly, params Type[] assignableTypes)
    {
        List<Type> types = new List<Type>();
 
        if (assembly != null)
            foreach (Type type in assembly.GetTypes())
                foreach (Type baseType in GetBaseTypesFromType(type, assignableTypes))
                    if (!types.Contains(baseType)) types.Add(baseType);
 
        return types;
    }
 
    public static List<Type> GetBaseTypesFromType(Type type, params Type[] assignableTypes)
    {
        List<Type> types = new List<Type>();
 
        foreach (Type assignableType in assignableTypes)
        {
            if (assignableType != type && assignableType.IsAssignableFrom(type))
            {
                types.Add(type);
                break;
            }
        }
 
        if (type.BaseType != null)
           types.AddRange(GetBaseTypesFromType(type.BaseType, assignableTypes));
 
        return types;
    }
}


Here's what the call looks like:
List<Type> plugins = TypeFinder.GetTypesFromAssembly(assembly, typeof(IMyPlugin), typeof(MyAbstractClass), typeof(MyBaseClass);

© 2008, D. Patrick Caldwell, Vice President for Research and Development, Emerald Software Group, LLC

No comments:

Post a Comment