Vishful thinking…

A generic factory utility class

Posted in Uncategorized by viswaug on September 5, 2007

Some of the projects I had worked on before required the ability to plug-in different components or features to the application after deployment. This was easily achieved using the Provider Model Design Pattern. But I found myself rewriting the method to create the objects from the type information. With .NET 2.0 and generics, I was able to write a an utility class that can create any type of object requested as a generic parameter. Writing the utility class was simple enough as can be seen below.

    public class Factory

    {

 

        #region “Private Members”

            AssemblyElementCollection _assemblyCollection;

        #endregion

 

        #region “Properties Members”

 

            public AssemblyElementCollection AssemblyCollection

            {

                get { return _assemblyCollection; }

            }

 

        #endregion

 

        #region “Constructors”

 

            public Factory(AssemblyElementCollection passemblyCollection)

            {

                _assemblyCollection = passemblyCollection;

            }

 

        #endregion

 

        #region “Public Methods”

 

            public T Create<T>(string pkey, params object[] pargs) where T : class

            {

                Type currentType = typeof(T);

                if (!(currentType.IsClass || currentType.IsInterface))

                {

                    throw new ArgumentException(“The Create function can only be called on interfaces and classes.”, “T”);

                }

 

                foreach (AssemblyElement ae in AssemblyCollection)

                {

                    if (ae.Key == pkey)

                    {

                        Assembly a = Assembly.Load(ae.FileName);

                        foreach (Type typ in a.GetTypes())

                        {

                            if (ae.ClassName == typ.Name)

                            {

                                object obj = Activator.CreateInstance(typ, pargs);

 

                                if(obj.GetType() == currentType)

                                {

                                    return obj as T;

                                }

                                else

                                {

                                    throw new InvalidCastException(“Cannot convert object of type [“ + obj.GetType().FullName + “] to [“ + currentType.FullName + “].”);

                                }

                            }

                        }

                    }

                }

 

                return null;

            }

 

        #endregion

 

    }

 

The core of the above sample is the Create<T>(…) functions that takes the type to be created as the generic parameter. The generic parameter of the function can either be an interface or a class as required. The “pkey” argument of the function that identifies the name of the entry in the configuration section. The “pargs” argument can be used to pass any arguments to the constructor of the type being created. This argument can be set to NULL if the constructor of the type being created does not take any arguments. An “InvalidCastException” will be thrown if the generic parameter type specified cannot be assigned from the object created. The configuration classes “AssemblyElement” and “AssemblyElementCollection” classes referenced in the above sample can be found in the project that can be downloaded here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: