I would like to dynamically execute a method on a class that uses a generic type, after finding it using reflection (which looks for an interface implementation).
An example of where I am stuck is below. Help is much appreciated.
Setup
public interface IActionRequired<T> where T : class {
void DoThis(T[] receivedObjects);
}
public class BookDetails {
public int BookId { get; set; }
public string BookName { get; set; }
}
public class LibraryBookReturned : IActionRequired<BookDetails>
{
public void DoThis(BookDetails[] receivedObjects)
{
foreach(var book in receivedObjects)
System.Console.WriteLine(book.BookName);
}
}
Example Attempt Using Reflection
Below, I am just using the first implementation but in the real world I'll be using a naming convention to locate the correct implementation.
var assembly = Assembly.GetCallingAssembly();
var listOfImplementations =
GetAllTypesImplementingOpenGenericType(typeof(IActionRequired<>), assembly);
var implementation = listOfImplementations.FirstOrDefault();
var implementationUsesInterface = implementation.GetInterfaces() [0];
var interfaceUsesType = implementationUsesInterface.GetGenericArguments() [0];
I understand that the below will not work (I get an error saying interfaceUsesType is a variable not a type) but it indicates what I would like to do:
var instance =
assembly.CreateInstance(implementation.FullName) as IActionRequired<interfaceUsesType>;
var results = this.CheckForMessages<interfaceUsesType>();
instance.DoThis(results);