13.9. Dynamically Invoking Members
Problem
You have a list of method names that you wish to invoke dynamically within your application. As your code executes, it will pull names off this list and attempt to invoke these methods. This technique might be useful to create a test harness for components that reads in the methods to execute from an XML file and executes them with the given arguments.
Solution
The TestDynamicInvocation method shown in Example 13-3 calls the DynamicInvoke method, which opens the XML configuration file, reads out the test information using LINQ, and executes each test method dynamically.
Example 13-3. Invoking members dynamically
public static void TestDynamicInvocation()
{
XDocument xdoc = XDocument.Load
(@"..\..\SampleClassLibrary\SampleClassLibraryTests.xml");
DynamicInvoke(xdoc, @"SampleClassLibrary.dll");
}The XML document in which the test method information is contained looks like this:
<?xml version="1.0" encoding="utf-8" ?> <Tests> <Test className='SampleClassLibrary.SampleClass' methodName='TestMethod1'> <Argument>Running TestMethod1</Argument> </Test> <Test className='SampleClassLibrary.SampleClass' methodName='TestMethod2'> <Parameter>Running TestMethod2</Parameter> <Parameter>27</Parameter> </Test> </Tests>
DynamicInvoke, as shown in Example 13-4,dynamically invokes the method that is passed to it using the information contained in the XDocument. Each parameter's type is determined by examining the ParameterInfo items on the MethodInfo, and then the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access