gpt4 book ai didi

c# - 如何在 .NET Core 中读取 connectionString WITH PROVIDER?

转载 作者:太空狗 更新时间:2023-10-29 21:21:26 26 4
gpt4 key购买 nike

我加了

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

 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,并且我希望它与连接字符串位于同一条目中,但不作为连接字符串。

最佳答案

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

以下是我建议如何将它们格式化为 json。与您使用旧的 XML app/web.config 方式指定连接字符串的方式非常相似。作为键的连接字符串的名称。

{
"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"
}
}
}

现在是要绑定(bind)的类。首先是简单的 ConnectionStringSettings 类本身,实现您的基本相等/散列方法(这是必要的,因为我们打算将其粘贴在字典中)。

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);
}
}

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

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;
}
}

最后是用法。

var configuration = new ConfigurationBuilder()
.AddJsonFile("config.json")
.Build();

var connectionStrings = configuration.ConnectionStrings();

foreach (var connectionString in connectionStrings.Values)
{
Console.WriteLine(connectionString.Name);
Console.WriteLine(connectionString.ConnectionString);
Console.WriteLine(connectionString.ProviderName);
}

var specificConnStr1 = connectionStrings["Test1"];
Console.WriteLine(specificConnStr1.Name);
Console.WriteLine(specificConnStr1.ConnectionString);
Console.WriteLine(specificConnStr1.ProviderName);

var specificConnStr2 = configuration.ConnectionString("Test2");
Console.WriteLine(specificConnStr2.Name);
Console.WriteLine(specificConnStr2.ConnectionString);
Console.WriteLine(specificConnStr2.ProviderName);

关于c# - 如何在 .NET Core 中读取 connectionString WITH PROVIDER?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40845542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com