Muokkaa

Jaa


Obtain a SqlClientFactory

Applies to: .NET Framework .NET .NET Standard

Download ADO.NET

The process of obtaining a DbProviderFactory involves passing information about a data provider to the DbProviderFactories class. Based on this information, the GetFactory method creates a strongly typed provider factory. For example, to create a SqlClientFactory, you can pass GetFactory a string with the provider name specified as "Microsoft.Data.SqlClient".

The other overload of GetFactory takes a DataRow. Once you create the provider factory, you can then use its methods to create additional objects. Some of the methods of a SqlClientFactory include CreateConnection, CreateCommand, and CreateDataAdapter.

Register SqlClientFactory

To retrieve the SqlClientFactory object by the DbProviderFactories class in .NET Framework, it's necessary to register it in a App.config or web.config file. The following configuration file fragment shows the syntax and format for Microsoft.Data.SqlClient.

<system.data>
  <DbProviderFactories>
    <add name="Microsoft SqlClient Data Provider"
      invariant="Microsoft.Data.SqlClient"
      description="Microsoft SqlClient Data Provider for SQL Server"
      type="Microsoft.Data.SqlClient.SqlClientFactory, Microsoft.Data.SqlClient, Version=2.0.20168.4, Culture=neutral, PublicKeyToken=23ec7fc2d6eaa4a5"/>
  </DbProviderFactories>
</system.data>  

The invariant attribute identifies the underlying data provider. This three-part naming syntax is also used when creating a new factory and for identifying the provider in an application configuration file so that the provider name, along with its associated connection string, can be retrieved at run time.

Note

In .NET core, since there is no GAC or global configuration support, the SqlClientFactory object should be registered by calling RegisterFactory method in the project.

The following sample shows how to use the SqlClientFactory in a .NET core application.

private static DbProviderFactory GetFactory()
{
    // register SqlClientFactory in provider factories
    DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient", SqlClientFactory.Instance);

    return DbProviderFactories.GetFactory("Microsoft.Data.SqlClient");
}

See also