Here’s the situation :
I want to create a test application which would be able to retrieve all the class and methods within a dll and allow me to call them at runtime.
What I have is something like this :
Let’s say I have those classes :
public static class FirstManagerSingleton
{
public static SecondManager Instance
{
return mInstance; // which is a SecondManager private static object
}
}
public class SecondManager
{
public Service1 service1 {get; private set;}
public Service2 service2 {get; private set;}
...
}
public class Service1
{
public bool Method1()
{
return true;
}
public int Method2()
{
return 1;
}
...
}
public class Service2
{
public bool Method1()
{
return false;
}
public int Method2(int aNumber)
{
return aNumber - 1;
}
...
}
I want to be able to select each “Service” Class, call any method and show its result.
Is it possible to do this using reflection ? If it wasn’t of the multiple layers (The 2 managers class) I wouldn’t struggle that much. The fact is I need to access the service class through a call which look like this :
FirstManagerSingleton.Instance.Service1.Method1;
So far, I’ve been able to load the assembly and retrieve almost every methods and print them.
Assembly assembly = Assembly.LoadFrom("assemblyName");
// through each type in the assembly
foreach (Type type in assembly.GetTypes())
{
// Pick up a class
if (type.IsClass == true)
{
MethodInfo[] methodInfo;
Console.WriteLine("Found Class : {0}", type.FullName);
Type inter = type.GetInterface("I" + type.Name, true);
if (inter != null)
{
methodInfo = inter.GetMethods();
foreach (MethodInfo aMethod in test2)
{
Console.WriteLine("\t\tMethods : " + aMethod);
}
}
}
}
From there, I don’t really know what to do next to invoke the methods.
By the way, those methods could take some parameters and have some return types.
I’m using the interface to retrieve the methods in order to filter from the methods inherited from another interface.
I hope I was clear enough. Sorry I can’t post the real code sample, but I guess it’s enough to illustrate the concept.
You should get the classes from the assemblies, then recursively get the property values and execute the methods. Here is some simple code that you should tailor according to your needs: