Using Reflection to call an overloaded method on a dynamically loaded assembly
I had some fun today! I have a factory class for database access (it handles the creation of classes from either System.Data.SqlClient or Oracle's Oracle.DataAccess). The Oracle.DataAccess assembly is dynamically loaded if it's needed. Consequently, I use reflection when I need to interact with the Oracle types.
Today, I had to call an overloaded method on the OracleParameterCollection object. The tricky part was that the second parameter was of a specific type -- OracleDbType (Oracle decided the System.Data.DbType wasn't good enough for them and had to make their own). Anyway, I needed to call:
OracleParameterCollection.Add(string name, OracleDbType dataType, object value, ParameterDirection direction);
For this particular case, I needed to pass OracelDbType.RefCursor for the second parameter -- via reflection. After a bit of trial & error along with googling, I finally got it! In the code below, "oracleDA" is an Assembly instance which references the dynamically loaded Oracle.DataAccess.DLL and "cmd" is my IDbCommand object which contains the Parameters collection:
// get the type info for an OracleDbType Type oracleDBType = oracleDA.GetType("Oracle.DataAccess.Client.OracleDbType"); // get a reference to the "RefCursor" member FieldInfo fi = oracleDBType.GetField("RefCursor"); // get the type info for the OracelParameterCollection Type oraParams = oracleDA.GetType("Oracle.DataAccess.Client.OracleParameterCollection"); // find the particular overloaded method we want to execute MethodInfo m = oraParams.GetMethod("Add", new Type[] {typeof(string), oracleDBType, typeof(object), typeof(ParameterDirection)}); // call the method to add the parameter m.Invoke(cmd.Parameters, new object[] { name, fi.GetValue(null), null, ParameterDirection.Output});