Add a DbProviderFactory without an App.Config
Asked Answered
C

8

42

I am using DbProviderFactories in my data layer (based on Entity Framework) and am using SQLite for my database, but I don't have to have a App.Config to have the following code:

<configuration>
  <system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SQLite"/>
      <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".Net Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
    </DbProviderFactories>
  </system.data>
</configuration>

Instead I would like to have my data layer put that in programmatically. Anyone know a way to do this?

EDIT:

The reason for this is that I am using a IoC container to pick the data layer and some of my data layers don't need the App.Config values, or have them be hard tied to the data layer.

Corporal answered 13/7, 2009 at 4:18 Comment(3)
Why don't you have an app.config. If you don't (maybe you're a class library), then the calling application does. Put the configuration there.Myself
Wondering if Jason ever found an answer to this... I've got an HTA which is calling our .Net assemblies as COM objects. So, there is no app.config. We're using SQL CE and we're facing the same issue.Astrodynamics
@JohnSaunders: For me, I was trying to make multiple exe's use the same configuration file. EntityFramework didn't seem to be honoring AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"C:\Shared\app.config"); Hence the usefulness of this question.Jeanicejeanie
O
60

The following will probably cause sunspots and overthrow western civilization. It may even cause a debate about Duct Tape Programming (make it stop!), but it works (for now)

try
{
    var dataSet = ConfigurationManager.GetSection("system.data") as System.Data.DataSet;
    dataSet.Tables[0].Rows.Add("SQLite Data Provider"
    , ".Net Framework Data Provider for SQLite"
    , "System.Data.SQLite"
    , "System.Data.SQLite.SQLiteFactory, System.Data.SQLite");
}
catch (System.Data.ConstraintException) { }
Obeah answered 4/11, 2009 at 0:0 Comment(1)
Hehe, it works. Not pretty, but it is the only thing out there. Thanks!Corporal
S
6

JoshRivers above posted a solution for SQLite. This can in fact be used for other adapters as well- I was able to get it working for MySQL using his example. I have wrapped this into something a bit more generic. This should be run once the application starts and is for the .NET connector version 6.6.5.0 (but I imagine it is good for other versions as well.)

string dataProvider = @"MySql.Data.MySqlClient";
string dataProviderDescription = @".Net Framework Data Provider for MySQL";
string dataProviderName = @"MySQL Data Provider";
string dataProviderType = @"MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.6.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d";

bool addProvider = true;
var dataSet = ConfigurationManager.GetSection("system.data") as DataSet;
foreach (DataRow row in dataSet.Tables[0].Rows)
{
    if ((row["InvariantName"] as string) == dataProvider)
    {
        // it is already in the config, no need to add.
        addProvider = false;
        break;
    }
}

if (addProvider)
    dataSet.Tables[0].Rows.Add(dataProviderName, dataProviderDescription, dataProvider, dataProviderType);
Southey answered 19/12, 2013 at 0:34 Comment(0)
M
5

LATE ANSWER:

You can always directly get a factory like this:

DbProviderFactory factory = System.Data.SQLite.SQLiteFactory.Instance;
// (note that the rest of the code is still provider-agnostic.)

Or use your IoC container to resolve the DbProviderFactory, e.g.:

container.RegisterInstance<DbProviderFactory>(SQLiteFactory.Instance);

I prefer not to use the DbProviderFactories.GetFactory because of its limitation of requiring a configuration file (or a hack like in @JoshRiver's answer).

All DbProviderFactories.GetFactory does is, it looks up the registered assembly-qualified name of the factory type using the provider name, and then it gets the value of the static Instance property using reflection.

If you don't want to use the configuration, one of the methods above might be more convenient depending on your use case.

Mannes answered 2/11, 2013 at 9:59 Comment(0)
F
3

Update for EF 6.0+

You can add a DbProviderFactory by registering a IDbDependencyResolver and resolving for the type DbProviderFactory. An example of this is below:

static class Program
{
    [STAThread]
    static void Main()
    {
        System.Data.Entity.DbConfiguration.Loaded += (_, a) => {
            a.AddDependencyResolver(new MyDependencyResolver(), true);
        };  

        Application.Run(new Form1());
    }
}

class MyDependencyResolver : System.Data.Entity.Infrastructure.DependencyResolution.IDbDependencyResolver {

    public object GetService(Type type, object key) {

        // Output the service attempting to be resolved along with it's key 
        System.Diagnostics.Debug.WriteLine(string.Format("MyDependencyResolver.GetService({0}, {1})", type.Name, key == null ? "" : key.ToString()));

        if (type == typeof(System.Data.Common.DbProviderFactory)) {

            // Return whatever DbProviderFactory is relevant
            return new MyDbProviderFactory(); 

        }else if(type == typeof(System.Data.Entity.Infrastructure.IProviderInvariantName) && key != null && key == "MyDbProviderFactory"){

            // Return the Provider's invariant name for the MyDbProviderFactory
            return new MyProviderInvariantName();

        }

        return null;
    }

    public IEnumerable<object> GetServices(Type type, object key) {
        return new object[] { GetService(type, key) }.ToList().Where(o => o != null);
    }
}

you may have to resolve for some additional types as well depending upon what type of overriding you're needing to do and how your project is setup. Basically just start with the code above and continue to debug until you've determined all the services you need to resolve for given your specific requirements.

You can read more about EF dependency resolution at the links below:

Additionally, you can do this configuration by overriding DbConfiguration as described in the first link above.

Fortepiano answered 25/8, 2014 at 16:12 Comment(0)
C
3

In .NET Core 2.1 and later you can use DbProviderFactories.RegisterFactory to programmatically register a DbProviderFactory.

Connive answered 6/5, 2019 at 0:22 Comment(1)
RegisterFactory does not exist in .NET 5 for unknown reason. I posted it in #65465568Panslavism
A
2

Chosing the DB provider factory programmatically pretty much defeats the purpose. You might as well use the classes specific to SQLite instead of all of those interfaces, no?

Acescent answered 13/7, 2009 at 4:31 Comment(1)
Actually, it's quite useful when your app.config is not being read, which is the case when you use F# interactive.Johnjohna
T
0

see the following snippet

    public DataProviderManager(string ProviderName)
    {

       var  _Provider = DbProviderFactories.GetFactory(ProviderName);

    }

you need to pass the ProviderName that in your case is "System.Data.SQLite".

you don't need to create the app config section. That section is created by SQLite in the machine.config after the SQLite.net provider is installed.

the whole purpose of the appconfig section is to help you get the list of configured .net providers when you call the following command:

public GetProvidersList() { DataTable table= DbProviderFactories.GetFactoryClasses(); }

Tatary answered 4/5, 2011 at 20:25 Comment(0)
S
0

Even Later Answer

Get it using configuration like above. I've found that this seems to require the provider assembly to be somewhere that the running program can find it.

    /// <summary>
    /// Creates a DbProviderFactory instance without needing configuration file
    /// </summary>
    /// <param name="lsProviderName">Name of the provider.  Like "System.Data.SQLite"</param>
    /// <param name="lsClass">Class and assembly information.  Like "System.Data.SQLite.SQLiteFactory, System.Data.SQLite"</param>
    /// <returns>A specific DbProviderFactory instance, or null if one can't be found</returns>
    protected static DbProviderFactory GetDbProviderFactoryFromConfigRow(string lsProviderName, string lsClass)
    {
        if (string.Empty != lsProviderName && string.Empty != lsClass)
        {
            DataRow loConfig = null;
            DataSet loDataSet = ConfigurationManager.GetSection("system.data") as DataSet;
            foreach (DataRow loRow in loDataSet.Tables[0].Rows)
            {
                if ((loRow["InvariantName"] as string) == lsProviderName)
                {
                    loConfig = loRow;
                }
            }

            if (null == loConfig)
            {
                loConfig = loDataSet.Tables[0].NewRow();
                loConfig["InvariantName"] = lsProviderName;
                loConfig["Description"] = "Dynamically added";
                loConfig["Name"] = lsProviderName + "Name";
                loConfig["AssemblyQualifiedName"] = lsClass;
                loDataSet.Tables[0].Rows.Add(loConfig);
            }

            try
            {
                DbProviderFactory loDbProviderFactoryByRow = DbProviderFactories.GetFactory(loConfig);
                return loDbProviderFactoryByRow;
            }
            catch (Exception loE)
            {
                //// Handled exception if needed, otherwise, null is returned and another method can be tried.
            }
        }

Another method that gets the Instance field directly from the assembly. It works even when the DLL is somewhere else on the system.

    /// <summary>
    /// Creates a DbProviderFactory instance without needing configuration file
    /// </summary>
    /// <param name="lsClass">Class and assembly information.  Like "System.Data.SQLite.SQLiteFactory, System.Data.SQLite"</param>
    /// <param name="lsAssemblyFile">Full path to the assembly DLL. Like "c:\references\System.Data.SQLite.dll"</param>
    /// <returns>A specific DbProviderFactory instance, or null if one can't be found</returns>
    protected static DbProviderFactory GetDbProviderFactoryFromAssembly(string lsClass, string lsAssemblyFile)
    {
        if (lsAssemblyFile != string.Empty && lsClass != string.Empty)
        {
            Assembly loAssembly = System.Reflection.Assembly.LoadFrom(lsAssemblyFile);
            if (null != loAssembly)
            {
                string[] laAssembly = lsClass.Split(new char[] { ',' });
                Type loType = loAssembly.GetType(laAssembly[0].Trim());
                FieldInfo loInfo = loType.GetField("Instance");
                if (null != loInfo)
                {
                    object loInstance = loInfo.GetValue(null);
                    if (null != loInstance)
                    {
                        if (loInstance is System.Data.Common.DbProviderFactory)
                        {
                            return loInstance as DbProviderFactory;
                        }
                    }
                }
            }
        }

        return null;
    }
Succinate answered 29/12, 2016 at 17:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.