Objective of this article:

In this article I am trying to dynamically instantiate an object at runtime using the XML. This concept is not new. The Unity Framework and Spring framework use similar techniques to create an object instance at runtime.

I have tried here to create a custom way of doing something similar. In order to create the instance at runtime I use the Activator.CreateInstance Method. More on this can found in the following link:
http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

Let's get into the code.

I have created a sample class named ClassA.

Code for the class is as shown below:

public class ClassA
    {
            private int factor;
            public ClassA()
            {
            }

            public ClassA(int f)
            {
              factor = f;
            }

            public int SampleMethod(int x)
            {
                Console.WriteLine("\nExample.SampleMethod({0}) executes.", x);
                return x * factor;
            }
    }


I then go ahead and create a class named Container. This is the class that will read from the XML the Class Name for which I want to create an instance. I have a static method Createinstance() which will perform that task for me.

Using the XmlTextReader I am reading the XML. Then using reflection I try to read the Assembly name. I parse through the XML to read the Name attribute. For your reference this is how the XML looks:

Sample.xml

<?xml version="1.0" encoding="utf-8" ?>
<Object type="Class" Name="XMLReader.ClassA"></Object>

Note: For the Name attribute I am providing the Fully Qualified name i.e AssemblyName.ClassName  (XMLReader.ClassA)

Code for the Container class looks as follows:

public static  class Container
    {
      public static Type CreateInstance()
      {
          XmlTextReader reader = new XmlTextReader("C:\\SimpleDI\\XMLReader\\XML\\Sample.xml");
          Assembly assem = Assembly.GetExecutingAssembly();

          AssemblyName assemName = assem.GetName();
          Console.WriteLine(assemName);

          while (reader.Read())
          {
              switch (reader.NodeType)
              {
 
                  case XmlNodeType.Element: // The node is an Element
                   
                      Console.WriteLine("Element: " + reader.Name);

                      Type type = null;
                      while (reader.MoveToNextAttribute())
// Read attributes

                          if (reader.Name == "Name")
                          {
                              type = assem.GetType(reader.Value); // typeName is a string
                          }
 
                      return type;
      
              }
          }

          reader.Close();
          Console.ReadLine();
          return null;
      }
    }

Finally in the Program.cs I try to create the object instance as shown in the code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml; // Imported for XMLTextReader
using System.Reflection;

namespace XMLReader
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly assem = Assembly.GetExecutingAssembly();

            AssemblyName assemName = assem.GetName();
            Console.WriteLine(assemName);        
 
            object obj = Activator.CreateInstance( Container.CreateInstance());
 
 
            MethodInfo m = Container.CreateInstance().GetMethod("SampleMethod");
            Object ret = m.Invoke(obj, new Object[] { 42 });
            Console.ReadLine();
        
        }
    }
}


Output for the Program looks as follows :

Dymanmic.gif
 

Next Recommended Readings