Saturday, 2 November 2013

Calling a method present in dll with out adding reference to project using Reflection

In this article we are going to see how to execute the method present in the dll, with out reference inside the project using Reflection.Reflection is used to load the dll in runtime and expose the methods , properties etc.

first create a Dll using class library project with following code,

  public class Operation
    {
        public bool IsReadOnly
        {
            get { return false; }
        }

        public int Addition(params int []vals)
        {
            int temp = 0;
            foreach (var eachnum in vals)
            {
                temp += eachnum;
            }
            return temp;
        }

        public int Subtraction(int val1, int val2)
        {
            try
            {
                return val1 - val2;
            }
            catch
            {
                return -1;
            }
        }
    }



This class operation consists of two methods one for addition and another for subtraction, Now a dll is generated Mathematics.dll





Now create a Console application which is used to load the dll at runtime , and execute the subtracion at runtime with out adding reference.


static void Main(string[] args)
        {
            Assembly assem_refer = Assembly.LoadFrom(@"D:\Project\StyleManager\Assembly_Reference\Mathematics.dll");
            Type typ = assem_refer.GetTypes()[0];
            object obj = Activator.CreateInstance(typ);

            /* Fetch the method info */
            MethodInfo []method = typ.GetMethods();
            Console.WriteLine();
            Console.WriteLine("Methods are present in Dll exposed using Reflection");
            Console.WriteLine();
            /* Execute the method */
            foreach (MethodInfo meth in method)
            {
                Console.WriteLine(meth.Name);   
            }
            Console.WriteLine();
            //executing a method
            MethodInfo sub =method.Where(x=>x.Name=="Subtraction").First();
            Console.WriteLine("Method Name :" + sub.Name);
            object[] param = new object[] { 5, 3 };
            var result = sub.Invoke(obj, param);
            Console.WriteLine("Values passed as Parameter {0},{1} Result is {2} ", 5, 3, result);

            Console.Read();
        }





Output  :



From this article you can learn how to load dll in runtime.




No comments:

Post a Comment