0

I'm trying to load a DLL runtime and invoke a method in one of the classes present in DLL.

Here is where I've loaded the DLL and invoking method,

Object[] mthdInps = new Object[2]; 
mthdInps[0] = mScope; 
string paramSrvrName = srvrName; 
mthdInps[1] = paramSrvrName; 
Assembly runTimeDLL = Assembly.LoadFrom("ClassLibrary.dll"); 
Type runTimeDLLType = runTimeDLL.GetType("ClassLibrary.Class1"); 
Object compObject = Activator.CreateInstance(runTimeDLLType, mthdInps); 
Type compClass = compObject.GetType(); 
MethodInfo mthdInfo = compClass.GetMethod("Method1"); 
string mthdResult = (string)mthdInfo.Invoke(compObject, null);

Here is the Class(present in DLL) and its method I'm trying to invoke,

namespace ClassLibrary
{
    public class Class1
    {
        public Class1()   {}
        public String Method1(Object[] inpObjs)
        {
        }
    }
}

The error I'm getting is this, Constructor on type 'ClassLibrary.Class1' not found.

Please help.

pravprab
  • 2,301
  • 3
  • 26
  • 43
wesfaith
  • 157
  • 1
  • 6
  • possible duplicate of [Loading DLLs at runtime in C#](http://stackoverflow.com/questions/18362368/loading-dlls-at-runtime-in-c-sharp) – Alexei Levenkov Mar 10 '14 at 02:12

3 Answers3

3

Seems that you're passing the method parameters to the class constructor.

This:

Object compObject = Activator.CreateInstance(runTimeDLLType, mthdInps); 

Should be just:

Object compObject = Activator.CreateInstance(runTimeDLLType); 

And then, you call the method with the parameters:

string mthdResult = (string)mthdInfo.Invoke(compObject, new object[] { objs });
thepirat000
  • 12,362
  • 4
  • 46
  • 72
1

The second argument of Activator.CreateInstance(Type, Object[]) specifies parameters to the constructor. You need to modify your constructor to take Object[], or call it with just the Type, Activator.CreateInstance(Type), then call your method passing in the object array.

See msdn documentation.

aw04
  • 10,857
  • 10
  • 56
  • 89
0

Try this:

Object[] mthdInps = new Object[2]; 
mthdInps[0] = mScope; 
string paramSrvrName = srvrName; 
mthdInps[1] = paramSrvrName; 
Assembly runTimeDLL = Assembly.LoadFrom("ClassLibrary.dll"); 
Type runTimeDLLType = runTimeDLL.GetType("ClassLibrary.Class1"); 
//do not pass parameters if the constructor doesn't have 
Object compObject = Activator.CreateInstance(runTimeDLLType); 
Type compClass = compObject.GetType(); 
MethodInfo mthdInfo = compClass.GetMethod("Method1"); 

// one parameter of type object array
object[] parameters = new object[] { mthdInps };
string mthdResult = (string)mthdInfo.Invoke(compObject, parameters );
Mihai Hantea
  • 1,741
  • 13
  • 16