Question

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.

Was it helpful?

Solution

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 });

OTHER TIPS

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.

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 );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top