Click here to Skip to main content
15,889,216 members
Articles / Programming Languages / C#

Make your application extensible with Reflection

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
20 Sep 2010CPOL1 min read 7.5K   3  
Make your application extensible with Reflection

Sometimes I'm very thankful when an application is extensible. It allows you to customize an application or event extends an application in an easy way. Otherwise, if the code is public, I have to dig 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 knowhow is missing?

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

C#
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;
}

Sure 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 responsibility builder!

Bookmark and Share DotnetKicks dotnetshoutout

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
-- There are no messages in this forum --