Make your application extensible with Reflection

Sometimes I’m very thankful when a application is extensible. It allows you to customize a application or event extend a application in a easy way. Otherwise, if the code is public, I have to digg through the code and search for a place where I can add my functionality. If I’m speaking about extensible I mean it in a technical manner where normally dependency injection frameworks will be used. But what do you use in a small application where you don’t have MEF, some “old” .NET 3.5 app, and a dependency injection framework like Structuremap is too big or the know how is missing? 

If you only want to provide extensibity, which means load all object of a specific type and process a action foreach object in a generic way, why not use old, classic reflection?

public static List<T> LoadAll<T>()
{
    List<T> services = new List<T>();

    foreach (Type type in Assembly.GetCallingAssembly().GetTypes())
    {
        if (type.IsSubclassOf(typeof(T)) && !type.IsAbstract && !type.IsInterface)
        {
            services.Add((T)Activator.CreateInstance(type));
        }
    }

    return services;
}

Shure you have to adapt your class design (it only works with empty constructors) and have to implement additional interfaces if you want to split a group with the same base class, but it’s simple, everyone knows what it does and how to handle. I used the code above in several projects (sometimes I thought i would exchange it later with a real dependency injection framework, which never happened) and also in my generic chain of responsibilty builder!

2 thoughts on “Make your application extensible with Reflection

  1. Nice approach, but I think there is a bug in this code. We should make some break after service was added in this line: services.Add((T)Activator.CreateInstance(type));
    Does it make sense?

  2. @Slava: No it should be correct like it is. If you would add a break after the add, it would leave the foreach loop and always only one service is added (but i want them all)

Comments are closed.