Extendable/optional function using reflection


Sometimes there is requirement that we need to provide functions, which can be extended/implemented by the client as per their needs. We can put the template for that method in separate .dll and can call using reflection. Reflection is very powerful in this scenario. I am assuming that you have basic knowledge of reflection.

 

Following is the template of the function, which will be provided, in separate DLL (here name is ReflectionExample.dll). Users can implements the code as per their requirements

 

using System;

 

namespace ReflectionExample

{

    public class UserClass

    {

        public UserClass()

        {

        }

        public string UserFunction(string str1)

        {

            //To be implemented by user as per his/her need. e.g getting/submit the data from database

            return "SUCCESS";

        }

    }

}

 

Following code call the ReflectionExample.dll. If reflectionExample.dll found in executable directory, code extended by user will execute. Otherwise it will return error in exception message.

 

private void button3_Click(object sender, System.EventArgs e)

{

    string strData="";

    try

    {

        Type aType;

        Assembly asmExample = Assembly.LoadFrom("ReflectionExample.dll");

        aType = asmExample.GetType("ReflectionExample.UserClass");

        object objReturn;

        try

        {

            objReturn = Activator.CreateInstance(aType);

            object[] objArgs = new Object[] {"Anand"};

            object objResult = aType.InvokeMember("UserFunction",BindingFlags.InvokeMethod,null,objReturn,objArgs);

            strData = objResult.ToString();

        }

        catch (Exception exp1)

        {

            strData = "FAILED" + " :- " + exp1.Message;

        }

    }

    catch(Exception exp2)

    {

        strData = "FAILED" + " :- " + exp2.Message;

    }

    MessageBox.Show(strData);

}


Similar Articles