Question

This is a study project. I have three database classes A,B,C. There is a factory class that receives thru its constructor which class's object to create. Each of the three classes[A,B,C] has a constructor with a parameter to supply the database connection object. This is the code I'm using in the factory class's createObject method:

Type classtyp = Type.GetType(className);

Type[] constrParam = new Type[1];
constrParam[0] = typeof(DBConnection);
ConstructorInfo constr = database.GetConstructor(constrParam);

return constr.Invoke(constrParam) as Database;

The last line above gives this error.

"Object of type 'System.RuntimeType' cannot be converted to type 'System.Data.Common.DbConnection'."

How did the 'System.RuntimeType' get here? I'm trying to create an object of class A which has a constructor that takes a variable of type DBconnection.

Currently I'm passing to the factory class instructions to create an instance of class A only. This the code of class A:

public class SqlServerDB: Database
{
    string str = "";

    public SqlServerDB(DbConnection DBConn)
        : base(DBConn)
    {
        str = "SQLServer";
    }
}

What am I doing wrong?

Thanks.

Was it helpful?

Solution

The Invoke method takes the object(s) that you need to pass into the constructor. You're passing in the type DbConnection. What you should be passing in, is an instance of DbConnection.

To be a bit more clear, if you were directly creating one of these objects, you'd do something like this:

DbConnection connection = GetConnection(); //some method that gives you back a connection object
SqlServerDB db = new SqlServerDB(connection);

What you're doing though is the same as doing this:

Type type = typeof(DbConnection);
SqlServerDB db = new SqlServerDB(type); //This is obviously wrong.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top