jeudi 16 mai 2019

Using Activator.CreateInstance to create instance of a class and inject Interface to constructor

My goal is to create an instance of a class from it's AssemblyQualifiedName. The problem is that this class requires an interface to be passed in it's constructor and I am having trouble doing this with Activator.CreateInstance.

Thanks in advance for the help.

Once i have the AssemblyQualifiedName of the class I want to instantiate I got it's type using Type.GetType(AQN), used that type to find the constructor and get the required parameters.

I get stuck when calling Activator.CreateInstance and passing the parameters.


var objectType = Type.GetType(AQN);

var constructors = objectType.GetConstructors();

    foreach (ConstructorInfo constructor in constructors)
                {
          var parameters = constructor.GetParameters(); 

          var instantiatedObj = Activator.CreateInstance(objectType,parameters);

                }


```c#

Once I do this i get the error "Constructor on Type xxx not found."





Aucun commentaire:

Enregistrer un commentaire