How to invoke a MethodInfo from a Dictionary without having the original method type?

Viewed 127

I'm working on a project that takes user defined methods and uses them to interact with some data.

Right now, I have something like this:

(Main)

 ...
 string dllFile = @"C:\Path\GenericTester" + commandValue + ".dll";
 var assembly = Assembly.LoadFile(dllFile);

 var type = assembly.GetType("DllNamespace.DllClass");

 string methodName = "FunctionForProperty" + commandValue; //commandValue is a string of a number

 var method = type.GetMethod(methodName);

 PropertiesDictionary.updateValue(int.Parse(commandValue), method);
 ...

On the PropertiesDictionary class:

static public class PropertiesDictionary
{
   public static Dictionary<int, MethodInfo> PropertiesMethods = new Dictionary<int, MethodInfo>();
                                                       
   public static void updateValue(int propertyId, MethodInfo method)
   {
      PropertiesMethods[propertyId] = method;
   }

   public static MethodInfo doFunctionForProperty(int propertyId)
   {                                         
      if (PropertiesMethods.ContainsKey(propertyId))
             return PropertiesMethods[propertyId];
      else
             return null;
   }
        
}

So, I'm trying to do something like this:

 MethodInfo method = ProjectNamespace.PropertiesDictionary.doFunctionForProperty(PropertyId);
 var result = method.Invoke(null, new object[] { ParametersOfTheFunctionOfTheDll });
 return result;

By the time I call that last lines I will no longer have access to the DLL (because we want in a future to just pass compiled code as System.Reflection.Assembly Load(byte[]) and we will access to that information just once)

The problem is obviously that I'm not passing the object target to the method.Invoke(), like var obj = Activator.CreateInstance(type);, but I think I don't know what type I should be pointing to.

Is there maybe a cleaner way to achieve what I want? Like, passing the whole method to the Dictionary from a class in System.Reflection.Assembly Load(byte[]) and not just the MethodInfo, so I can invoke it wherever I want without having to pass the target?

1 Answers

I just solved this problem by setting the user defined methods as static, so I don't have to pass the target anymore. However I think this isn't the best solution, but for now it works for me.

Related