Thursday, December 15, 2022

Singleton Data configuration with JSON file for connection strings information

 Singleton Data configuration with JSON file for connection strings information

public class SingletonDataConfig

{

private static readonly Lazy<SingletonDataConfig> _config = 

new Lazy<SingletonDataConfig>(() => 

new SingletonDataConfig(), System.Threading.LazyThreadSafetyMode.PublicationOnly);

private IConfiguration DataConfig { get; } = new ConfigurationBuilder().

AddJsonFile("yourDatabaseSettings.json").Build();

public static SingletonDataConfig Instance => _config.Value;

private string _connstringinfo

public string ConnStringInfo {

get {

var conn  = DataConfig.GetConnectionString("YourConnStringName");

string pwd = DataConfig ["DbPassword"].ToString();

SqlConnectionStringBuilder connBuilder = new SqlConnectionsStringBuilder(conn);

builder.Add("Password", pwd);

_connstringinfo = builder.ConnectionString;

}

return _connstringinfo 

}

}

How to reference the above Singleton Class in your connection string?

using (SqlConnection conn = new SqlConnection(SingletonDataConfig.Instance.ConnStringInfo))

{

....

}

Source Code reference for Singelton - https://csharpindepth.com/articles/singleton