Objective of this Article

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

Here, I have tried 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 be found in the following link:

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 which will perform the operation of reading 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 read the XML. Then using reflection concept, 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:

image001.jpg
推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"