I have a .dll and a console app that uses the said .dll but doesn't reference directly,
it loads it via reflection. The console app calls a method of a class inside the .dll.
The method signature is IEnumerable<Customer> GetAll()
;
In the .dll I have done this:
class CustomerRepository : ICustomerRepository
{
public IEnumerable<Customer> GetAll()
{
using (var db = new DB02Context())
{
List<Customer> list = new List<Customer>();
// some queries to fill the list
return list;
}
}
}
In the Console app I've done this:
Assembly assembly = Assembly.LoadFrom(pathToMyDLL);
Type t = assembly.GetType("MyDLL.Models.CustomerRepository");
var methodInfo = t.GetMethod("GetAll");
if(methodInfo == null)
throw new Exception("The method doesn't exists");
var customerRepository = Activator.CreateInstance(t);
// Invoke the GetAll() method
var customerList = methodInfo.Invoke(customerRepository, null);
Now the question is, since GetAll returns IEnumerable<Customer>
and my console app
doesn't "know" anything about MyDLL.dll (I don't reference it directly, so it doesn't knows the Customer
type).
How can I access to the Customer list in order to access Customer'a properties without having to make a reference to the .dll explicitly?
You have three options
Client
or move a interface Client
implements to a 3rd dll that both the reflected DLL and your console app can reference.dynamic
keyword as the type of the object (dynamic customerList = methodInfo.Invoke(...
), this is the exact situation it was invented for.IEnumerable
and use reflection calls to call the methods in Client
on the object
objects the IEnumerable
returns.As everything is inside the DLL that you load dynamically, the first and fastest thing that comes to mind is to cast the GetAll as an IEnumerable<dynamic>
and use the properties accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With