在.NET Core中选择合适的DbProviderFactory?

时间:2018-08-21 20:25:22

标签: c# .net-core dbproviderfactories

我有一个.net核心库,需要将DbProviderFactory作为依赖项传递到服务中。在可预见的将来应该是SQL Server,所以我认为我可以做这样的事情:

services.AddSingleton<IMyService>(di=>new MyService(SqlClientFactory.Instance));

...但是我的appsettings.json文件中有多个数据库连接字符串,并且我没有看到一种机制来告诉Instance使用哪个连接。

如何配置DbProviderFactory以使用正确的连接和连接字符串? appsettings文件中没有连接或提供者的“名称”概念。

1 个答案:

答案 0 :(得分:0)

配置中的连接字符串设置有一个provider property。如果在本地配置了正确的提供程序,则可以按以下方式使用它:

  

[System.Configuration.ConfigurationProperty(“ providerName”,   DefaultValue = Mono.Cecil.CustomAttributeArgument)]公共字符串   ProviderName {get;组; }

<connectionStrings>
    <add name="Example" 
         providerName="System.Data.SqlClient" 
         connectionString="Data Source=1.1.1.1;Integrated Security=True"/>
</connectionStrings>

可以这样称呼:

DbProviderFactories.GetFactory(settings.ProviderName);

通常,如果您只有一个DBConnection,则可以创建一个辅助方法来检索ProviderFactory:

public static DbProviderFactory GetProviderFactory(DbConnection connection)
{
    DbProviderFactory providerFactory = null;
    Type connectionType = connection.GetType();
    BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;

    // Check for DbConnection.DbProviderFactory
    PropertyInfo providerFactoryInfo = connectionType.GetProperty("DbProviderFactory", flags);
    if (providerFactoryInfo != null)
        providerFactory = (DbProviderFactory)providerFactoryInfo.GetValue(connection, null);

    // Check for DbConnection.ConnectionFactory.ProviderFactory
    if (providerFactory == null)
    {
        PropertyInfo connectionFactoryInfo = connectionType.GetProperty("ConnectionFactory", flags);
        object connectionFactory = connectionFactoryInfo.GetValue(connection, null);
        providerFactoryInfo = connectionFactory.GetType().GetProperty("ProviderFactory", flags);
        providerFactory = (DbProviderFactory)providerFactoryInfo.GetValue(connectionFactory, null);
    }

    // No match
    if (providerFactory == null)
        throw new InvalidOperationException("ProviderFactory not found for connection");

    return providerFactory;
}

但是.NET核心不包含反射,因此这是开箱即用的。