SIGN UP MEMBER LOGIN:    
ARTICLE

Dynamic Loading of Objects Using XML

Posted by Mahadesh Mahalingappa Articles | XML in C# June 26, 2011
In this article I am trying to dynamically instantiate an object at runtime using the XML.
Reader Level:
Download Files:
 


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
 

Login to add your contents and source code to this article
share this article :
post comment
 

Good work, thanks for sharing

Posted by Dinesh Beniwal Jun 26, 2011
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Team Foundation Server Hosting
Become a Sponsor