Question

I don't want to modify my machine.config, but I want to use the Npgsql library as a data provider. I will deploy my application to multiple platforms (including mono) so I would really like the thing to "just work" instead of giving me the error "Unable to find the requested .Net Framework Data Provider."

Is there a way to "register" Npgsql as a data provider at runtime so this does not happen?

I should clarify that Npgsql works fine without it being in my machine.config for most things, but there are some it does not work well for (like NLog -- the current source of my frustration).

Was it helpful?

Solution

I found out how to do what I needed done; it's not quite "runtime" but close enough and I didn't have to modify my machine.config. I added this section to my web.config file:

<system.data>
    <DbProviderFactories>
        <add name="Npgsql Data Provider" invariant="Npgsql" description=".NET Framework Data Provider for PostgreSQL" type="Npgsql.NpgsqlFactory, Npgsql" />
    </DbProviderFactories>
</system.data>

...and it started working like a champ.

OTHER TIPS

You will have to resort to using Reflection (the code is for Microsoft .NET Framework so you would have to verify if the private field is the same in Mono).

using System.Data.Common;

// 1. Initialize the default configuration
DbProviderFactories.GetFactoryClasses();

// 2. Retrieve the configuration table.
var config = (DataTable)typeof(DbProviderFactories).GetField("_providerTable", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);

// 3. Add a new entry in the configuration (replace the values with ones for your provider).
DataRow dataRow = config.NewRow();
dataRow["Name"] = "SqlClient Data Provider";
dataRow["InvariantName"] = typeof(SqlConnection).Namespace.ToString();
dataRow["Description"] = ".Net Framework Data Provider for SqlServer";
dataRow["AssemblyQualifiedName"] = typeof(SqlConnection).AssemblyQualifiedName;
config.Rows.Add(dataRow);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top