[Mono-list] Assembly.LoadFrom() - Assembly.CreateInstance() - Activator.CreateInstanceFrom() ---> invalid cast

Jaroslaw Kowalski jaroslaw.kowalski@atm.com.pl
Mon, 26 Jan 2004 11:08:58 +0100


For MSSQL I do (watch for line breaks):

Type t = Type.GetType("System.Data.SqlClient.SqlConnection, System.Data,
Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")

IDbConnection conn = (IDbConnection)Activator.CreateInstance(t);

Note, that Type.GetType() needs:

1. Local assembly name when the assembly is in application directory.
2. Fully qualified assembly name when the assembly is in the GAC or you want
to take specific advantage of the assembly binding redirection.

To get the fully qualified assembly name from GAC it's best to use: "gacutil
/l"

Jarek

----- Original Message ----- 
From: "Timothy Parez" <timothyparez@linux.be>
To: <mono-list@ximian.com>
Sent: Sunday, January 25, 2004 8:04 PM
Subject: [Mono-list] Assembly.LoadFrom() - Assembly.CreateInstance() -
Activator.CreateInstanceFrom() ---> invalid cast


> Hey,
>
> This isn't mono specific, but there're a lot of smart people in this
> list so here I go :)
> Something simular is probably in the Mono sources but I don't really get
it
>
> I'm trying to load DataProviders at runtime (defined by XML files which
> are in the ..\plugin directory of the application)
>
> First I would like to know what the difference is between
>
> Assembly.CreateInstance() and Activator.CreateInstanceFrom()
> As far as I can see they both to the same even though one is in the
> reflection namespace and the other in the remoting namespace.
>
> Second this code I can't get to work:
>
> Assembly DataProvider;
> DataProvider = Assembly.LoadFrom(@"bytefx\ByteFX.Data.dll");
> object dbConnection =
>
DataProvider.CreateInstance("ByteFX.Data.MySqlClient.MySqlConnection",false)
;
> MessageBox.Show(dbConnection.ToString()); // Outputs:
> "ByteFX.Data.MySqlClient.MySqlConnection"
> IDbConnection dbConn = (IDbConnection)dbConnection; // This throws an
> exception --> Invalid cast
>
> But MySqlConnection implements IDbConnection, it really does :)
>
> I also tried this instead:
>
>             object conn = Activator.CreateInstanceFrom(
> @"ByteFX.Data.dll","ByteFX.Data.MySqlClient.MySqlConnection").Unwrap();
>             MessageBox.Show(conn.ToString());
>             IDbConnection dbConnection = (IDbConnection)conn;
>
> This has exactly the same result, the message box shows the right name,
> but I get an invalid cast in the next line.
>
> How can I solve this ?
>
> Thnx.
> Timothy.
>
> _______________________________________________
> Mono-list maillist  -  Mono-list@lists.ximian.com
> http://lists.ximian.com/mailman/listinfo/mono-list
>