I have a main project that uses a plugin architecture. The main project cannot know about the plugins. For this, I am using https://web.archive.org/web/20170506195518/http://www.squarewidget.com:80/pluggable-architecture-in-asp.net-mvc-4
While I don't fully understand what this is doing, it does work for me.
What I need to do now is to call a method in an unrelated DLL. I have an example method...
namespace MyPlugins.Controllers
{
public class Calculate
{
public float Add(float a, float b)
{
return a + b;
}
}
}
I want to call it, by only knowing its name (as a string), such like...
string MethodToCall = "MyPlugins.Controllers.Calculate.Add";
float a = 12.7F;
float ab = 123F;
dynamic result = CallMethod(MethodToCall, new object[] { a, ab });
For this, I have looked and tried various methods, but none of them are working for me. Here is my current CallMethod.
public dynamic CallMethod(string Method, object[] Params = null)
{
string[] MethodPath = Method.Split('.');
try
{
string MethodType = MethodPath[0];
if (MethodPath.Length > 2)
{
for (int i = 1; i < MethodPath.Length - 1; i++)
{
MethodType += "." + MethodPath[i];
}
}
Type t = Type.GetType(MethodType);
Type[] myObjects = new Type[Params.Count()];
for (int i = 0; i < Params.Length; i++)
{
myObjects[i] = Type.GetType(Params[i].GetType().FullName);
}
var methodInfo = t.GetMethod(MethodPath[MethodPath.Length - 1], myObjects);
if (methodInfo == null)
{
// never throw generic Exception - replace this with some other exception type
throw new Exception("No such method exists.");
}
var o = Activator.CreateInstance(t);
object[] parameters = new object[Params.Length];
for (int i = 0; i < Params.Length; i++)
{
parameters[i] = Params[i];
}
var r = methodInfo.Invoke(o, parameters);
return r;
}
catch
{
return null;
}
}
The problem I am seeing is that the Type.GetType(MethodType) always returns null.
My thoughts are that as I am using the SquareWidget example (link above), is that the assembly is loaded so should just be able to call it.
Thank you for your help.