How to plug-in a DLL into a C# project

John Grove share a code at MSDN on how can we call DLLs methods dynamically using C# code.

The below code can further be modified and a developer can easily extend the functionality of his application to create a application which accepts DLLs as plug-ins. This concept is useful when different users have different requirements in a generalized application like in the case of famous photo editing program Photoshop from Adobe. Here anyone can create a plug-in and hook it up with the host application which further inherits all the functionalities from the DLL.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ConsoleApplication1
    class Program
        static void Main(string[] args)
            Assembly assembly = Assembly.LoadFrom(@"C:\Documents and Settings\john.grove\MyMath.dll");
            Type mathUtility = assembly.GetType("MyMathUtilty");
            Object theInstance = Activator.CreateInstance(mathUtility);
            Int32 result = (Int32)mathUtility.InvokeMember("Add", BindingFlags.InvokeMethod, null, theInstance, new object[] { 56, 26 });
            Console.WriteLine("Dynamically invoking MyMathUtilty Add method");
            Console.WriteLine("56 + 26 = {0}", result);
            // get all public static methods of MyMathUtilty type
            MethodInfo[] methodInfos = mathUtility.GetMethods(BindingFlags.Public | BindingFlags.Static);
            Console.WriteLine("All public/static methods in MyMathUtilty");
            for (Int32 i = 0; i < methodInfos.Count(); i++ )
                Console.WriteLine("{0}.) {1}", i + 1, methodInfos[i].Name);
comments powered by Disqus