I am new to this so please bear with me. I have been exploring C# for
a few months, but I am only just getting into ASP.NET. Today I came
across the DBProviderFactory Class. I have been searching online for
an answer to my question without any luck. My question is this.
What is the point? What is the advantage of this code...
DbProviderFactory sqlClientFactory =
DbProviderFactories.GetFactory("System.Data.Client");
DbConnection cn1 = sqlClientFactory.CreateConnection();
when I can just use this code?
SqlConnection cn2 = new SqlConnection();
Is the first way necessay when developing ASP.NET websites as opposed
to developping Windows Forms applications?
Help is always appreciated. Thanks in advance.
Paul
> What is the point? What is the advantage of this code...
>
> (DbProviderFactory code was here)
>
> when I can just use this code?
>
> SqlConnection cn2 = new SqlConnection();
The quick answer is: If you know you’re going to need an SqlConnection always and forever
in your code, there’s no advantage at all. But what if you want your code to be able to use either an
SqlConnection, or an OracleConnection? Then you want to use a DBProviderFactory to let the code determine
which connection to use, rather than hardcoding in some sort of switching logic.
Quoting from: http://msdn2.microsoft.com/en-us/library/wda6c36e.aspx
Working with Factories
The System.Data.Common namespace provides classes for creating DbProviderFactory instances to work with specific databases. When you create a DbProviderFactory instance, passing it information about the provider along with the connection string, the instance can determine the correct strongly-typed object to return based on the information it has been provided. This lets you write code that is not dependent on the data provider and lets you choose the provider at runtime.
All sorts of musing over the Factory Design Pattern at http://msdn2.microsoft.com/en-us/library/ms954600.aspx as well.
And a comparison article from the archives J is at http://msdn2.microsoft.com/en-us/library/ms379620(VS.80).aspx
NOTE: Before I read your request, a few minutes ago, I had no idea these DBFactory things existed. J Seemed like a reasonable question to look up, though. J
_____
Peter Smith
Paul