lundi 23 octobre 2017

Activator.CreateInstance gives MissingMethodException

I have this few lines:

private Type providerType; // this DOES get a value before using CreateNewProperty so it isn't null.

public IUniqueProperty CreateNewProperty(PropertyInfo propertyInfo, 
   Type containerClassType)
{
    var obj = (IUniqueProperty)Activator.CreateInstance(providerType); //this line gives the error.
    obj.ID = RequestID;
    obj.PropertyInfo = propertyInfo;
    obj.ContainerClassType = containerClassType;
    properties.Add(obj);
    return obj;
}

And the line I marked with a comment gives me the following error message:

MissingMethodException: Method not found: 'Default constructor not found...ctor() of Assets.Helper.UniquePropertyProvider'. System.Activator.CreateInstance (System.Type type, Boolean nonPublic) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Activator.cs:368) System.Activator.CreateInstance (System.Type type) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Activator.cs:254) Assets.Helper.PropertyFactory.CreateNewProperty (System.Reflection.PropertyInfo propertyInfo, System.Type containerClassType) (at Assets/Helper/PropertyFactory.cs:55) Assets.ViewModelBase.MatchProperty (Assets.Bindable b) (at Assets/ViewModelBase.cs:135) Assets.ViewModelBase.Connect (System.Collections.Generic.List`1 bindables) (at Assets/ViewModelBase.cs:172) Assets.ViewModelBase..ctor (Assets.View v) (at Assets/ViewModelBase.cs:24) Assets.Test.TestViewModel..ctor (Assets.View v) (at Assets/Test/TestViewModel.cs:11) Assets.Test.TestBL.Awake () (at Assets/Test/TestBL.cs:14)

Basically telling me it has found no constructor. The intention with this one is that I want to create an interface, so when instantiating the class this CreateNewProperty is in, I pass in a type that implements that interface and I want to instantiate a class of the given type I passed in, but eventually returning it as an interface. Question is, what is the problem?

edit

The method is called like

var newProp = propertyFactory.CreateNewProperty(p, item.GetType());

and the PropertyFactory in the making is instantiated like this:

propertyFactory = new PropertyFactory(typeof(UniquePropertyProvider));

And the type to instantiate:

public class UniquePropertyProvider : IUniqueProperty
{
    private int id;
    private PropertyInfo propertyInfo;

    public UniquePropertyProvider(int id, PropertyInfo propertyInfo)
    {
        this.id = id;
        this.propertyInfo = propertyInfo;
    }

    public int ID
    {
        get { return id; }
        set { id = value; }
    }

    public PropertyInfo PropertyInfo
    {
        get { return propertyInfo; }
        set { propertyInfo = value; }
    }

    public Type ContainerClassType { get; set; }
}





Aucun commentaire:

Enregistrer un commentaire