I am using Reflection in the following manner: a) Loading the assembly b) Getting all the methods and their respective parameters c) invoking the methods
There are not issues faced while invoking methods which take input type as primitive datatypes(int,double,string etc) I tried invoking the method in 2 ways:
(object)method.Invoke(obj,respar);
where respar is an array of input parameters
object cu = Activator.CreateInstance(typeof(Customer)) as Customer;
respar.SetValue(cu, i);//i = index
and
(object)type.InvokeMember(methodName, BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Default,null, obj, respar);
Where
object obj = Activator.CreateInstance(type,true);//obj
In the first case I am getting an Argument Exception Error and in the second case I am getting Method not found Exception.
For example If I invoke a method say GetCustomer(Customer data) where Customer is a class, the above errors are thrown.
Let me explain in detail: There is one class CustomerModel
public class CustomerModel
{
public string FirstName{get;set;}
public string LastName {get;set;}
}
And Customer Class
public class Customer
{
public CustomerModel GetCustomerDetails(CustomerTable tableobj)
{
//TODO: Get customer details from tableobj and pass to CustomerModel Obj
}
}
I am trying to invoke all methods of this customer class through reflection. There is another class Test:
public class Test
{
public void GetAllMethodsInassembly()
{
//Load assembly
//Get all classes
// Foreach Class=> get all methods
//Invoke each method => get result and store in XML file
}
}
The method in Customer GetCustomerDetails which is throwing an exception as mentioned. Please suggest.
It looks like you've referenced the assembly with the Customer type directly as well as tried to load it dynamically using
Assembly.LoadFile
. I would try doing something like this to get the assembly and invoke methods in it:If you insist on loading the assembly dynamically and referencing it, you've got to understand assembly binding contexts or you will keep running into the same problem.
Assembly binding contexts are isolated, in-memory assembly caches.
Load
(the "default"),LoadFrom
, andLoadFile
all use different contexts. The same type from the same assembly loaded in different context are considered different by the runtime. When a referenced assembly is loaded it is bound in the default "Load" context.Another option may be to use the
Assembly.Load
and provide the assembly name. If the assembly is strong-named another option may be toLoad
it earlier and then useLoadFrom
later, becauseLoadFrom
will check if an assembly with the same name has already been loaded intoLoad
context before loading it from the specified file.