Skip to content

Instantly share code, notes, and snippets.

@edouardp
Created June 27, 2016 08:09
Show Gist options
  • Save edouardp/6838937454c03da6202f3dbf59b75013 to your computer and use it in GitHub Desktop.
Save edouardp/6838937454c03da6202f3dbf59b75013 to your computer and use it in GitHub Desktop.
Helper to make using DbProviderFactories.GetFactory() easier to use with dynamic provider loading (no app.config required)
class DbProviderHelper
{
const string AssemblyQualifiedName = "AssemblyQualifiedName";
const string Name = "Name";
const string InvariantName = "InvariantName";
const string Description = "Description";
internal class FactoryInfo
{
public string InvariantName { get; set; }
public string AssemblyQualifiedName { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public List<FactoryInfo> Factories { get; set; }
public string DbProvider { get; set; }
public string ConnectionString { get; set; }
DbProviderFactory m_factory;
public DbProviderHelper()
{
Factories = new List<FactoryInfo>();
var factories = DbProviderFactories.GetFactoryClasses();
foreach (DataRow dataRow in factories.Rows) {
var info = new FactoryInfo {
InvariantName = dataRow [InvariantName] as string,
Name = dataRow [Name] as string,
AssemblyQualifiedName = dataRow [AssemblyQualifiedName] as string,
Description = dataRow [Description] as string
};
Factories.Add(info);
}
}
public bool InvariantNamePresentInFactories(string invariantName)
{
return Factories.Count(f => f.InvariantName == invariantName) > 0;
}
public DbConnection CreateConnection()
{
if (DbProvider == null)
throw new ApplicationException("No DbProvider dude!");
if (ConnectionString == null)
throw new ApplicationException("No ConnectionString dude!");
if (m_factory == null)
{
if (InvariantNamePresentInFactories(DbProvider))
{
// Look up factory via InvariantName
m_factory = DbProviderFactories.GetFactory(DbProvider);
}
else
{
// Look up factory via QualifiedAssemblyName (in a DataRow)
var table = new DataTable();
var column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = AssemblyQualifiedName;
table.Columns.Add(column);
var row = table.NewRow();
row [AssemblyQualifiedName] = DbProvider;
m_factory = DbProviderFactories.GetFactory(row);
}
}
var connection = m_factory.CreateConnection();
connection.ConnectionString = ConnectionString;
connection.Open();
return connection;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment