.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Dynamic Loading of objects using XML

Posted By:Mahadesh Mahalingappa       Posted Date: June 25, 2011    Points: 200    Category: C#    URL: http://www.dotnetspark.com  

In this article I am trying 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
 

Dynamic Loading of objects using XML :
 

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 . 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 . Inorder 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

Lets 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 as 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 am reading 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();

        }
    }
}

 Subscribe to Articles

     

Further Readings:

Responses
Author: Amit Mehra         Company URL: http://www.dotnetspark.com
Posted Date: June 28, 2011

Nice article Mahadesh..Thanks for sharing your knowledge..Hope to see many more articles..

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend