如何在.NET Core中读取带有PROVIDER的connectionString?

时间:2016-11-28 13:30:22

标签: c# asp.net-core asp.net-core-mvc .net-core asp.net-core-1.0

我添加了

.AddJsonFile("Connections.json", optional: true, reloadOnChange: true)

in

 public Startup(IHostingEnvironment env)

Connections.json包含:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=DATABASE;Trusted_Connection=True;MultipleActiveResultSets=true",
    "COR-W81-101": "Data Source=DATASOURCE;Initial Catalog=P61_CAFM_Basic;User Id=USERID;Password=PASSWORD;Persist Security Info=False;MultipleActiveResultSets=False;Packet Size=4096;",
    "COR-W81-100": "Data Source=DATASOURCE;Initial Catalog=Post_PS;User Id=USERID;Password=PASSWORD;Persist Security Info=False;MultipleActiveResultSets=False;Packet Size=4096;",
    "MSEDGEWIN10": "Data Source=DATASOURCE; Initial Catalog=COR_Basic; Persist Security Info=False;Integrated Security=true;MultipleActiveResultSets=False;Packet Size=4096;Application Name=\"COR_Basic\"",

    "server": "Data Source=DATASOURCE; Initial Catalog=COR_Basic; Persist Security Info=False;User Id=USERID;Password=PASSWORD;MultipleActiveResultSets=False;Packet Size=4096;Application Name=\"COR_Basic\""
  },


  "conStrings": [
      {
        "name": "COR-W81-101",     
        "connectionString": "Data Source=DATASOURCE; Initial Catalog=COR_Basic; Persist Security Info=False;Integrated Security=true;MultipleActiveResultSets=False;Packet Size=4096;Application Name=\"COR_Basic\"",
        "providerName": "System.Data.SqlClient"
      }

    },

    {
      "name": "server",
      "connectionString": "Data Source=DATASOURCE; Initial Catalog=COR_Basic; Persist Security Info=False;Integrated Security=true;MultipleActiveResultSets=False;Packet Size=4096;Application Name=\"COR_Basic\"",
      "providerName": "System.Data.SqlClient"
    }
  ],



  "conStringDictionary": {
    "COR-W81-101": {
      "connectionString": "Data Source=DATASOURCE; Initial Catalog=COR_Basic; Persist Security Info=False;Integrated Security=true;MultipleActiveResultSets=False;Packet Size=4096;Application Name=\"COR_Basic\"",
      "providerName": "System.Data.SqlClient"
    },

    "server": {
      "connectionString": "Data Source=DATASOURCE; Initial Catalog=COR_Basic; Persist Security Info=False;Integrated Security=true;MultipleActiveResultSets=False;Packet Size=4096;Application Name=\"COR_Basic\"",
      "providerName": "System.Data.SqlClient"
    }

  }
}

现在我想阅读connectionStrings:

public class ConnectionString
{
    public string name { get; set; }
    public string connectionString { get; set; }
    public string providerName { get; set; }
}
像这样:

//Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions.Configure<ConnectionString[]>(services, Configuration.GetSection("conStrings"));

// https://stackoverflow.com/questions/31929482/retrieve-sections-from-config-json-in-asp-net-5
//var objectSections = Configuration.GetSection("conStringDictionary").GetChildren();
//foreach (var x in objectSections)
//{
//    System.Console.WriteLine(x.Key);
//    var cs = new ConnectionString();
//    ConfigurationBinder.Bind(x, cs);
//    System.Console.WriteLine(cs);
//}

// http://andrewlock.net/how-to-use-the-ioptions-pattern-for-configuration-in-asp-net-core-rc2/
        Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions.Configure<Dictionary<string, ConnectionString>>(services, Configuration.GetSection("conStrings"));

但我无法读取数组或字典。我需要每个connectionString的providerName,我希望它与连接字符串在同一条目中,但不是作为连接字符串。

4 个答案:

答案 0 :(得分:7)

你基本上就在那里,你所要做的就是创建一些强类型的类来匹配旧的ConnectionStringSettings并使用一些集合序列化逻辑。

以下是我建议在json中格式化它们的方法。与您如何使用旧的XML app / web.config方式指定连接字符串类似。作为密钥的连接字符串的名称。

contains

现在要绑定的类。首先是简单的ConnectionStringSettings类本身,实现你的基本相等/散列方法(因为我们打算将它粘在一个字典中,所以必须这样做)。

{
  "ConnectionStrings": {
    "Test1": {
      "ConnectionString": "server=localhost;database=db;username=user;password=pass;",
      "ProviderName": "MySql.Data.MySqlClient"
    },
    "Test2": {
      "ConnectionString": "server=localhost;database=db2;username=user2;password=pass2;",
      "ProviderName": "MySql.Data.MySqlClient"
    }
  }
}

接下来是ConnectionStringSettings的集合。这只是必需的,因为连接字符串的名称是JSON表示法中的键。为了保持该名称的一致性,我们需要覆盖Dictionary的Add方法(但你不能这样做,因为它不是虚拟的)。所以我们真正做的只是在内部用我们自己的Add实现中的额外位包装一个Dictionary。这看起来像很多代码,但你会发现它是非常单调无聊的东西。

public class ConnectionStringSettings
{
    public String Name { get; set; }
    public String ConnectionString { get; set; }
    public String ProviderName { get; set; }

    public ConnectionStringSettings()
    {
    }

    public ConnectionStringSettings(String name, String connectionString)
        : this(name, connectionString, null)
    {
    }

    public ConnectionStringSettings(String name, String connectionString, String providerName)
    {
        this.Name = name;
        this.ConnectionString = connectionString;
        this.ProviderName = providerName;
    }

    protected bool Equals(ConnectionStringSettings other)
    {
        return String.Equals(Name, other.Name) && String.Equals(ConnectionString, other.ConnectionString) && String.Equals(ProviderName, other.ProviderName);
    }

    public override bool Equals(Object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((ConnectionStringSettings) obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hashCode = (Name != null ? Name.GetHashCode() : 0);
            hashCode = (hashCode * 397) ^ (ConnectionString != null ? ConnectionString.GetHashCode() : 0);
            hashCode = (hashCode * 397) ^ (ProviderName != null ? ProviderName.GetHashCode() : 0);
            return hashCode;
        }
    }

    public static bool operator ==(ConnectionStringSettings left, ConnectionStringSettings right)
    {
        return Equals(left, right);
    }

    public static bool operator !=(ConnectionStringSettings left, ConnectionStringSettings right)
    {
        return !Equals(left, right);
    }
}

一些简单的扩展方法,使事情变得更简单。

public class ConnectionStringSettingsCollection : IDictionary<String, ConnectionStringSettings>
{
    private readonly Dictionary<String, ConnectionStringSettings> m_ConnectionStrings;

    public ConnectionStringSettingsCollection()
    {
        m_ConnectionStrings = new Dictionary<String, ConnectionStringSettings>();
    }

    public ConnectionStringSettingsCollection(int capacity)
    {
        m_ConnectionStrings = new Dictionary<String, ConnectionStringSettings>(capacity);
    }

    #region IEnumerable methods
    IEnumerator IEnumerable.GetEnumerator()
    {
        return ((IEnumerable)m_ConnectionStrings).GetEnumerator();
    }
    #endregion

    #region IEnumerable<> methods
    IEnumerator<KeyValuePair<String, ConnectionStringSettings>> IEnumerable<KeyValuePair<String, ConnectionStringSettings>>.GetEnumerator()
    {
        return ((IEnumerable<KeyValuePair<String, ConnectionStringSettings>>)m_ConnectionStrings).GetEnumerator();
    }
    #endregion

    #region ICollection<> methods
    void ICollection<KeyValuePair<String, ConnectionStringSettings>>.Add(KeyValuePair<String, ConnectionStringSettings> item)
    {
        ((ICollection<KeyValuePair<String, ConnectionStringSettings>>)m_ConnectionStrings).Add(item);
    }

    void ICollection<KeyValuePair<String, ConnectionStringSettings>>.Clear()
    {
        ((ICollection<KeyValuePair<String, ConnectionStringSettings>>)m_ConnectionStrings).Clear();
    }

    Boolean ICollection<KeyValuePair<String, ConnectionStringSettings>>.Contains(KeyValuePair<String, ConnectionStringSettings> item)
    {
        return ((ICollection<KeyValuePair<String, ConnectionStringSettings>>)m_ConnectionStrings).Contains(item);
    }

    void ICollection<KeyValuePair<String, ConnectionStringSettings>>.CopyTo(KeyValuePair<String, ConnectionStringSettings>[] array, Int32 arrayIndex)
    {
        ((ICollection<KeyValuePair<String, ConnectionStringSettings>>)m_ConnectionStrings).CopyTo(array, arrayIndex);
    }

    Boolean ICollection<KeyValuePair<String, ConnectionStringSettings>>.Remove(KeyValuePair<String, ConnectionStringSettings> item)
    {
        return ((ICollection<KeyValuePair<String, ConnectionStringSettings>>)m_ConnectionStrings).Remove(item);
    }

    public Int32 Count => ((ICollection<KeyValuePair<String, ConnectionStringSettings>>)m_ConnectionStrings).Count;
    public Boolean IsReadOnly => ((ICollection<KeyValuePair<String, ConnectionStringSettings>>)m_ConnectionStrings).IsReadOnly;
    #endregion

    #region IDictionary<> methods
    public void Add(String key, ConnectionStringSettings value)
    {
        // NOTE only slight modification, we add back in the Name of connectionString here (since it is the key)
        value.Name = key;
        m_ConnectionStrings.Add(key, value);
    }

    public Boolean ContainsKey(String key)
    {
        return m_ConnectionStrings.ContainsKey(key);
    }

    public Boolean Remove(String key)
    {
        return m_ConnectionStrings.Remove(key);
    }

    public Boolean TryGetValue(String key, out ConnectionStringSettings value)
    {
        return m_ConnectionStrings.TryGetValue(key, out value);
    }

    public ConnectionStringSettings this[String key]
    {
        get => m_ConnectionStrings[key];
        set => Add(key, value);
    }

    public ICollection<String> Keys => m_ConnectionStrings.Keys;
    public ICollection<ConnectionStringSettings> Values => m_ConnectionStrings.Values;
    #endregion
}

最后用法。

public static class ConnectionStringSettingsExtensions
{
    public static ConnectionStringSettingsCollection ConnectionStrings(this IConfigurationRoot configuration, String section = "ConnectionStrings")
    {
        var connectionStringCollection = configuration.GetSection(section).Get<ConnectionStringSettingsCollection>();
        if (connectionStringCollection == null)
        {
            return new ConnectionStringSettingsCollection();
        }

        return connectionStringCollection;
    }

    public static ConnectionStringSettings ConnectionString(this IConfigurationRoot configuration, String name, String section = "ConnectionStrings")
    {
        ConnectionStringSettings connectionStringSettings;

        var connectionStringCollection = configuration.GetSection(section).Get<ConnectionStringSettingsCollection>();
        if (connectionStringCollection == null ||
            !connectionStringCollection.TryGetValue(name, out connectionStringSettings))
        {
            return null;
        }

        return connectionStringSettings;
    }
}

答案 1 :(得分:1)

首先,Nicholi的回答启发了我!谢谢Nicholi。

第二,我有一个“列表”解决方案,而不是IDictionary解决方案。它不像IDictionary解决方案那么顺利。

这也可以称为“如何为点网核心配置创建收集列表”

我们在这里:

首先是无耻的盗窃!

public class ConnectionStringEntry
{
    public String Name { get; set; }
    public String ConnectionString { get; set; }
    public String ProviderName { get; set; }

    public ConnectionStringEntry()
    {
    }

    public ConnectionStringEntry(String name, String connectionString)
        : this(name, connectionString, null)
    {
    }

    public ConnectionStringEntry(String name, String connectionString, String providerName)
    {
        this.Name = name;
        this.ConnectionString = connectionString;
        this.ProviderName = providerName;
    }
}

秒,一个“包装器”。我想跟踪DefaultConnectionStringName ...以及我的条目列表(集合)。

public class ConnectionStringWrapper
{
    public string DefaultConnectionStringName { get; set; } = "";
    public List<ConnectionStringEntry> ConnectionStringEntries { get; set; } = new List<ConnectionStringEntry>();
    //public Dictionary<string, ConnectionStringEntry> ConnectionStringEntries { get; set; } = new Dictionary<string, ConnectionStringEntry>();

    public ConnectionStringEntry GetDefaultConnectionStringEntry()
    {
        ConnectionStringEntry returnItem = this.GetConnectionStringEntry(this.DefaultConnectionStringName);
        return returnItem;
    }

    public ConnectionStringEntry GetConnectionStringEntry(string name)
    {
        ConnectionStringEntry returnItem = null;
        if (null != this.ConnectionStringEntries && this.ConnectionStringEntries.Any())
        {
            returnItem = this.ConnectionStringEntries.FirstOrDefault(ce => ce.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
        }

        if (null == returnItem)
        {
            throw new ArgumentOutOfRangeException(string.Format("No default ConnectionStringEntry found. (ConnectionStringEntries.Names='{0}', Search.Name='{1}')", this.ConnectionStringEntries == null ? string.Empty : string.Join(",", this.ConnectionStringEntries.Select(ce => ce.Name)), name));
        }

        return returnItem;
    }
}

现在,我正在阅读json并映射到具体的设置对象代码:

            IConfiguration config = new ConfigurationBuilder()
                    .SetBasePath(System.IO.Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .Build();


            ConnectionStringWrapper settings = new ConnectionStringWrapper();
            config.Bind("ConnectionStringWrapperSettings", settings);
            Console.WriteLine("{0}, {1}", settings.DefaultConnectionStringName, settings.ConnectionStringEntries.Count);
            ConnectionStringEntry cse = settings.GetDefaultConnectionStringEntry();

我的nuget包:

\.nuget\packages\microsoft.extensions.configuration\2.1.1
\.nuget\packages\microsoft.extensions.configuration.binder\2.1.1
\.nuget\packages\microsoft.extensions.configuration.json\2.1.1

以下奖励材料:

我想要(这样)支持一种代码库,可以将其部署为DotNet 4.x(现在称为“经典” ??)和dotnet核心。

为此,我已经编写了上面的内容,以提供DotNet(Classic)处理连接字符串(xml,我们的老朋友)和现在的新奇孩子的抽象方法:带有json的DotNetCore。

为此,我编写了一个界面:

public interface IConnectionStringWrapperRetriever
{
    ConnectionStringWrapper RetrieveConnectionStringWrapper();
}

我有一个dotnetcore的实现:

public class ConnectionStringWrapperDotNetCoreRetriever : IConnectionStringWrapperRetriever
{
    public const string ConnectionStringWrapperSettingsJsonElementName = "ConnectionStringWrapperSettings";

    private readonly IConfiguration config;

    public ConnectionStringWrapperDotNetCoreRetriever(IConfiguration cnfg)
    {
        this.config = cnfg;
    }

    public ConnectionStringWrapper RetrieveConnectionStringWrapper()
    {
        ConnectionStringWrapper settings = new ConnectionStringWrapper();
        this.config.Bind(ConnectionStringWrapperSettingsJsonElementName, settings);
        return settings;
    }
}

是的,所有重要的JSON设置:

{
  "ConnectionStringWrapperSettings": {
    "DefaultConnectionStringName": "abc",
    "ConnectionStringEntries": [
      {
        "Name": "abc",
        "ConnectionString": "Server=myserver;Database=mydatabase;Trusted_Connection=True;MultipleActiveResultSets=true",
        "ProviderName": "SomeProvider"
      },
      {
        "Name": "def",
        "ConnectionString": "server=localhost;database=db2;username=user2;password=pass2;",
        "ProviderName": "SomeProvider"
      }
    ]
  }
}

.............

对于DotNet(经典),您要做的就是为IConnectionStringWrapperRetriever实现第二个具体操作,然后神奇地完成。

还记得下面的xml吗? (哈哈,还不算老!)

<?xml version="1.0" encoding="utf-8"?>  
<configuration>  
  <connectionStrings>  
    <add name="ConnStr1" connectionString="LocalSqlServer: data source=127.0.0.1;Integrated Security=SSPI;Initial Catalog=aspnetdb"  
      providerName="System.Data.SqlClient" />  
  </connectionStrings>  
</configuration>  

(来自https://docs.microsoft.com/en-us/dotnet/api/system.configuration.connectionstringsettingscollection?view=netframework-4.7.2

还记得EnterpriseLibrary中的这些内容吗?

<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</configSections>

<dataConfiguration defaultDatabase="ConnStr1"/>

我将DotNet(Classic)实现留给读者。

但是现在我将IConnectionStringWrapperRetriever注入到DataLayer类中。
我正在使用Dapper,因此可以使用IConnectionStringWrapperRetriever钓鱼连接字符串。

如果我的项目是“ house” DotNet(Classic),则注入IConnectionStringWrapperRetriever的一个版本(此处未显示,留给读者)。如果我的项目被“安置”在DotNetCore中,我将注入第二个(如上所示)IConnectionStringWrapperRetriever版本。

在这篇文章的讨论范围之外,但是“安置”是指我有2个csproj并排坐着。

MyApp.DataLayer.classic.csproj 和 MyApp.DataLayer.csproj

我发现保留默认的csproj来容纳DotNetCore东西会更容易。我使用“ classic.csproj”文件来存放DotNet(classic)。我的程序集名称和默认名称空间仍为“ MyApp.Datalayer” .... csicproj文件名唯一的.classic是唯一的。

我也创建了两个解决方案sln文件。 MySolution.classic.sln和MySolution.sln。

它似乎在我上面编写的ConnectionString抽象中起作用。

我唯一有条件的是(经典)AssemblyInfo.cs文件。

#if(!NETCOREAPP2_1)

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

/* all the other stuff removed here */

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

#endif

APPEND:

好的,这是DotNet(Classic)版本:

public class ConnectionStringWrapperDotNetClassicRetriever : IConnectionStringWrapperRetriever
{
    public ConnectionStringWrapper RetrieveConnectionStringWrapper()
    {
        ConnectionStringWrapper returnItem = new ConnectionStringWrapper();

        foreach(ConnectionStringSettings css in System.Configuration.ConfigurationManager.ConnectionStrings)
        {
            ConnectionStringEntry cse = new ConnectionStringEntry(css.Name, css.ConnectionString, css.ProviderName);
            returnItem.ConnectionStringEntries.Add(cse);
        }

        if(returnItem.ConnectionStringEntries.Count == 1)
        {
            /* if there is only one, set the default name to that one */
            returnItem.DefaultConnectionStringName = returnItem.ConnectionStringEntries.First().Name;
        }
        else
        {
            /*
            <packages>
              <package id="EnterpriseLibrary.Common" version="6.0.1304.0" targetFramework="net45" />
              <package id="EnterpriseLibrary.Data" version="6.0.1304.0" targetFramework="net45" />
            </packages>                 
             */

            /* using Microsoft.Practices.EnterpriseLibrary.Data.Configuration; */
            /* You can write you own way to handle a default database, or piggyback off of EnterpriseLibrary.  You don't necessarily have to use EnterpriseLibrary.Data, you are simply piggybacking on their xml/configuration setup */
            DatabaseSettings dbSettings = (DatabaseSettings)ConfigurationManager.GetSection("dataConfiguration");
            returnItem.DefaultConnectionStringName = dbSettings.DefaultDatabase;
        }

        return returnItem;
    }
}

和app.config xml:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data"/>
  </configSections>

  <connectionStrings>
    <clear/>
    <add name="MyFirstConnectionStringName" connectionString="Server=.\MyServerOne;Database=OneDB;Trusted_Connection=True;MultipleActiveResultSets=true"
      providerName="System.Data.SqlClient" />

    <add name="MySecondConnectionStringName" connectionString="Server=.\MyServerTwo;Database=TwoDB;Trusted_Connection=True;MultipleActiveResultSets=true"
      providerName="System.Data.SqlClient" />
  </connectionStrings>


  <dataConfiguration defaultDatabase="MyFirstConnectionStringName" />

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

关键字:

DotNet DotNet .Net Core经典Json配置ICollection标量和集合同时支持dotnet和dotnetcore

答案 2 :(得分:0)

类似的东西:

  var configurationRoot = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", false)
                .Build();

 var conString = configurationRoot["ConnectionStrings:MyConnection"]);

答案 3 :(得分:0)

一个老问题,但是我今天正在看这个问题,以为我会分享...

包含ProviderName的简单替代方法

这是一个简单的替代方法,它避免了自定义扩展名并更改了默认的ConnectionStrings配置结构。它基于Microsoft如何在Azure上为应用程序包括ProviderName的方式。

解决方案是在ConnectionStrings部分中添加一个与上下文相关的键,以指定ProviderName。

AppSettings.json 和SQLite提供程序:

{  
  "ConnectionStrings": {
    "MyContext": "Data Source=c:\\MySqlite.db;Version=3;",
    "MyContext_ProviderName": "System.Data.SQLite",
  }
}

然后在C#代码中,使用GetConnectionString()方法读取值:

var connectionString = Configuration.GetConnectionString("MyContext");
var providerName = Configuration.GetConnectionString("MyContext_ProviderName") ?? "";

if (Regex.IsMatch(providerName, "SQLite", RegexOptions.IgnoreCase)) 
{
    builder.UseSqlite(connectionString);
}
else if (Regex.IsMatch(providerName, "Oracle", RegexOptions.IgnoreCase)) 
{    
    builder.AddOracle(connectionString);
}
else if (... 

奖金-连接字符串前缀

Microsoft包括SQLClient和MySQL的预定义前缀,它们将自动以上述格式包含提供程序名称。但是,这些前缀仅在作为环境变量添加时才起作用,即在appsettings.json中不起作用。例如,在launchSettings.json中使用 MYSQLCONNSTR _ 前缀定义连接字符串将同时填充连接字符串和提供程序名称。有关扣留,请参见Configuration in ASP.NET Core并向下滚动至连接字符串前缀

launchSettings.json

{
  "profiles": {
    "Development": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "",
      "environmentVariables": {
       "ASPNETCORE_ENVIRONMENT": "Development",

       // The prefix
       "MYSQLCONNSTR_MyContext": "Server=myServerAddress;Database=Green;Uid=myUsername;Pwd=myPassword;"

      }
    }
}