MissingMethodException: no parameterless constructor defined for this object

Sanmathi picture Sanmathi · Apr 14, 2014 · Viewed 8k times · Source

I am trying to call a class of a dll from my console application. All the classes which I am trying to call from the dll have parameterized constructors. I wish to pass user and pass as the two parameters to any class I am trying to invoke. I know there is something wrong with how I am invoking the methods, but am unable to figure out what.

Can someone please correct my code?

The error occurs in the line - "object instance = Activator.CreateInstance(type)"

Console app -

class Program
{
    static void Main(string[] args)
    {
        string test_method = args[2];
        string user = args[0];
        string pass = args[1];

        Assembly myassembly = Assembly.LoadFrom("Tests.dll");

        Type type = myassembly.GetType("Tests." + test_method);

        object instance = Activator.CreateInstance(type);
        MethodInfo[] methods = type.GetMethods();
        methods[0].Invoke(instance, new object[] {user, pass });

        Console.WriteLine("\n"+test_method + " has passed.");

    }
}

An example class which is being called -

public class Test_3456 : ePO
{
    public Test_3456(string a, string b) : base (a, b)
    {
        MultipleWebclipsSameNameDifferentUrl_3456();
    }

    [TestMethod]
    public void MultipleWebclipsSameNameDifferentUrl_3456()
    {
        PolicyCatalog.GoTo();
        PolicyCatalog.PolCatSelect("iOS (User-Based Policy)");

        WebClip.iOSWebClipsTab();
        WebClip.Add2WebClipsSameNameDifferentUrl();
        WebClip.Ok();
        WebClip.Save();
    }
}

The constructor here is a dummy constructor. The base class takes in the user and pass parameters.

Base class -

 public class ePO
{
    public ePO(string a, string b)
    {
        Init(a, b);
    }

    [TestInitialize]
    public void Init(string username, string password)
    {
        Driver.initialize();
        Login.GoTo();
        Login.LoginAs(username).WithPassword(password).Login();
    }
}

Answer

TheEvilPenguin picture TheEvilPenguin · Apr 14, 2014

As Activator.CreateInstance() creates the object, that's where you need to give the constructor parameters:

object instance = Activator.CreateInstance(type, new object[] {user, pass });