Friday 12 December 2008

How to ... find some types in application

There is no problem with finding some types in a concrete assembly, but recently I got stuck with more general problem. I needed to find some types in a whole application.

First concept was to load all assemblies placed in the /bin directory, one by one and then search for it. This should work, but what if somebody change the output folder? Yes, we can get output path from the framework but...

Second concept... I've started digging and found another solution, in fact much better then the first one.
From AppDomain class we can get collection of all loaded assemblies, but there is one catch - there are not only assembles referenced by the project but also all framework assemblies. If we iterate over them and store our results, it wouldn't be a problem.

In example I stored all types which are an interface.
I placed source code for that functionality below:

public class ClassLoader

{

    private static List<Type> loadedTypes;

    public static List<Type> LoadedTypes

    {

        get

        {

            if(loadedTypes == null)

                loadedTypes = LoadTypes();

            return loadedTypes;

        }

    }

 

    private static List<Type> LoadTypes()

    {

        Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

        return (from tp in assemblies.SelectMany

                    (assembly => assembly.GetTypes())

                where CheckCondition(tp)

                select tp).ToList();

    }

 

    private static bool CheckCondition(Type type)

    {

        return type.IsInterface;

    }

}



I hope it will be a help for someone,
Enjoy