For an application I'm building, I would like to inject an IDbConnection using structuremap. The problem here is two-fold:
Using different configurations (for deployment), I would like to use different providers. SqlServerCe for local and our develop server, and SqlServer for our Test and Production environments.
After injecting an IDbConnection, I've noticed that adding parameters to an
IDbCommand
is not as easy as I thought it would be: Depending on the connection type, I would either have to add aSystem.Data.SqlServerCe.SqlCeParameter
or aSystem.Data.SqlClient.SqlParameter
, rather than a generic parameter type.
The first problem, I "solved" by switching on the connection string's providerName, and then either injecting System.Data.SqlServerCe.SqlCeConnection
or System.Data.SqlClient.SqlConnection
, though this is in no way pretty, and I would like to have an alternative.
Code:
For<System.Data.IDbConnection>().Use(() =>
ConfigurationManager.ConnectionStrings["DefaultConnection"].ProviderName.Contains("SqlServerCe")
? (IDbConnection)new SqlCeConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)
: (IDbConnection)new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString));
The second problem seems to be more tricky. It would also depend on the provider, but seeing as I would need to provide a parametername and value to an instance of IDataParameter
at runtime, the above "sollution" doesn't seem feasable.
Then again, my initial way of doing this might be completely off as well.
Does anybody know how to best tackle these 2 issues? I'm not really all that great with structuremap (or DI in general), and might just be missing some very basic concepts.