简体   繁体   中英

Get type from assembly load using reflection

The project1 has class1 and interface1. Class1 implements the interface1. I have another project that will test this class1 methods using interface1. Now the catch is I have to load the project1.dll dynamically and use the interface methods to make calls to class1 methods. To do this, I am loading the project1.dll using reflection. Now, I get the methodInfo from the interface and before invoking this method, I should create an instance of the class that I will invoke the method. To create a instance of the class using activator.createInstance I need to know the constructor params. Now, these constructor params are of custom type. As I said earlier I have to load the dll's dynamically. So is there a way to get the type from the assembly load? Or any other approach to achieve the above idea? Below is my code.

Assembly assembly = Assembly.LoadFrom(@"D:\Project1.dll");
Type[] typeArray = assembly.GetTypes();
object obj;

//First create the instance of the class
foreach (Type type in typeArray)
{

    if (type.Name == "Class1")
    {

        Type[] types = new Type[4];

        //I am not able to get the below customParams from the loaded assembly.
        //Is there a way to do this. Can this be done without adding reference?
        types[0] = typeof(CustompParam1);
        types[1] = typeof(CustompParam2);
        types[2] = typeof(CustompParam3);
        types[3] = typeof(CustompParam4);

        obj = Activator.CreateInstance(types);
    }
}

//use the instance of the class to invoke the method from the interface
foreach (Type type in typeArray)
{
    if (type.Name == "Interface1")
    {
        MethodInfo[] mInfo = type.GetMethods();
        foreach (MethodInfo mi in mInfo)
        {
            mi.Invoke(obj, null);
        }
    }
}

You could get the instances for constructor parameters the same way you create your class instance

Find them by type name, the call Activator.CreateInstance for parameter type, and then put them into Activator.CreateInstance of your original class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM