Search This Blog

Wednesday, August 2, 2017

How to Dynamically load a class and execute a method in .NET

public class DynamicInvoke
{
    // this way of invoking a function
    // is slower when making multiple calls
    // because the assembly is being instantiated each time.
    // But this code is clearer as to what is going on
    public static Object InvokeMethodSlow(string AssemblyName,
           string ClassName, string MethodName, Object[] args)
    {
      // load the assemly
      Assembly assembly = Assembly.LoadFrom(AssemblyName);

      // Walk through each type in the assembly looking for our class
      foreach (Type type in assembly.GetTypes())
      {
        if (type.IsClass == true)
        {
          if (type.FullName.EndsWith("." + ClassName))
          {
            // create an instance of the object
            object ClassObj = Activator.CreateInstance(type);

            // Dynamically Invoke the method
            object Result = type.InvokeMember(MethodName,
              BindingFlags.Default | BindingFlags.InvokeMethod,
                   null,
                   ClassObj,
                   args);
            return (Result);
          }
        }
      }
      throw (new System.Exception("could not invoke method"));
    }

    // ---------------------------------------------
    // now do it the efficient way
    // by holding references to the assembly
    // and class

    // this is an inner class which holds the class instance info
    public class DynamicClassInfo
    {
      public Type type;
      public Object ClassObject;

      public DynamicClassInfo()
      {
      }

      public DynamicClassInfo(Type t, Object c)
      {
        type = t;
        ClassObject = c;
      }
    }


    public static Hashtable AssemblyReferences = new Hashtable();
    public static Hashtable ClassReferences = new Hashtable();

    public static DynamicClassInfo
           GetClassReference(string AssemblyName, string ClassName)
    {
      if (ClassReferences.ContainsKey(AssemblyName) == false)
      {
        Assembly assembly;
        if (AssemblyReferences.ContainsKey(AssemblyName) == false)
        {
          AssemblyReferences.Add(AssemblyName,
                assembly = Assembly.LoadFrom(AssemblyName));
        }
        else
          assembly = (Assembly)AssemblyReferences[AssemblyName];

        // Walk through each type in the assembly
        foreach (Type type in assembly.GetTypes())
        {
          if (type.IsClass == true)
          {
            // doing it this way means that you don't have
            // to specify the full namespace and class (just the class)
            if (type.FullName.EndsWith("." + ClassName))
            {
              DynamicClassInfo ci = new DynamicClassInfo(type,
                                 Activator.CreateInstance(type));
              ClassReferences.Add(AssemblyName, ci);
              return (ci);
            }
          }
        }
        throw (new System.Exception("could not instantiate class"));
      }
      return ((DynamicClassInfo)ClassReferences[AssemblyName]);
    }

    public static Object InvokeMethod(DynamicClassInfo ci,
                         string MethodName, Object[] args)
    {
      // Dynamically Invoke the method
      Object Result = ci.type.InvokeMember(MethodName,
        BindingFlags.Default | BindingFlags.InvokeMethod,
             null,
             ci.ClassObject,
             args);
      return (Result);
    }

    // --- this is the method that you invoke ------------
    public static Object InvokeMethod(string AssemblyName,
           string ClassName, string MethodName, Object[] args)
    {
      DynamicClassInfo ci = GetClassReference(AssemblyName, ClassName);
      return (InvokeMethod(ci, MethodName, args));
    }
  }

// Create an object array consisting of the parameters to the method.
// Make sure you get the types right or the underlying
// InvokeMember will not find the right method
Object [] args = {1, "2", 3.0};
Object Result = DynamicInvoke("Test.dll",
                "ClassName", "MethodName", args);
// cast the result to the type that the method actually returned.


Source :https://www.codeproject.com/Articles/13747/Dynamically-load-a-class-and-execute-a-method-in-N

No comments:

Post a Comment