2009-11-06

Generic Object Factory

The following class is a generic object factory. It is used for creating instances of objects from configured or otherwise provided strings.

The “User Guide” is in the comments.

/// <summary>
/// Generic object factory that creates instances of objects from configured or otherwise provided strings.
/// </summary>
public class ObjectFactory
{
    /// <summary>
    /// Creates an instance of a class from a string "[namespace.[...].className], [component without filname extension],[Version],[Culture],[…]".
    /// </summary>
    /// <typeparam name="T">The type to create.</typeparam>
    /// <param name="configuredClassAndAssembly">Format: [namespace.[...].className], [component without filname extension]</param>
    /// <returns>An object of type T.</returns>
    /// <remarks>This method uses generics!</remarks>
    public static T CreateClassInstance<T>(string configuredClassAndAssembly)
    {
        //Get type to instanciate
        Type tp = Type.GetType(configuredClassAndAssembly, true);

        //load assembly
        Assembly assembly = Assembly.GetAssembly(tp);

        //create class instance
        T instance = (T)assembly.CreateInstance(tp.FullName);

        //return instance
        return instance;
    }
}

I am using it to create instances of objects that implement certain interfaces, so that I can swap the implementation, or even mock it, by changing the configuration.

The string that tells which object to create uses the format of the Type.GetType(string) string.

Some error handling should be added.