Sunil
Sunil

Reputation: 21406

DbProviderFactory code relationship with code for creating a SqlConnection in ADO.Net

When I instantiate a SqlConnection object in ADO.Net, then does this code result in the execution of corresponding DbProviderFactory code ? So when the code in block 2 is executed by, then we actually end up executing code in block 1. But I am not sure if this is true.

CODE BLOCK 1 - Instantiate a SqlConnection using DbProviderFactory approach

DbProviderFactory factory =
DbProviderFactories.GetFactory(providerName);

connection = factory.CreateConnection();
connection.ConnectionString = connectionString;

CODE BLOCK 2 -Instantiate a SqlConnection using standard ADO.Net code

SqlConnection con = new SqlConnection(connectionString);

Upvotes: 1

Views: 5988

Answers (2)

JavaJoe127
JavaJoe127

Reputation: 31

To be sure what's going on, consider removing code block 2 - it isn't needed and adds complexity. Just use the factories capabilities to use the connection. For example, you have:

DbProviderFactory factory =
DbProviderFactories.GetFactory(providerName);

connection = factory.CreateConnection();
connection.ConnectionString = connectionString;

Add the following :

try
{
  connection.Open();
  var command = connection.CreateCommand();
  command.CommandText = "SELECT * FROM mytable";
  (..etc...)

We had to connect to MS SQL or Oracle, depending on user preference and this worked perfectly for us, the only thing unique will be the provider, connection string, and command text. Microsoft shows an example how to pull the providers from machine.config here.

Hope this helps, and if I'm incorrect, please let me know!

Upvotes: 3

Pilgerstorfer Franz
Pilgerstorfer Franz

Reputation: 8359

I had a look at some .net Framework assemblies and found the following

DbProviderFactories.GetFactory(providerName) will return an Factory object according to the given providerName. Let's assume providerName indicates an SQL Provider so we will get an SqlClientFactory.

Afterwards factory.CreateConnection() will be called. In this case SqlClientFactory.CreateConnection() will be called which is implemented as

public override DbConnection CreateConnection()
{
    return new SqlConnection();
}

I think the answer to your question is that calling the factory methods will call the methods of the provider specific classes and not the other way round!

Upvotes: 3

Related Questions