I have a use case where I will need multiple connection strings in my data access layer and will use anyone depending on the input.
Currently, I have 2 connection strings which I have added in JSON and then I am injecting both.
Is there any other solution to inject all the connection strings at once because in future with the introduction of any new DB I have to add one more connection string in JSON and then again inject it?
StartUp class:
private static void Main(string[] args)
{
ServiceCollection serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
IServiceProvider serviceProvider =
serviceCollection.BuildServiceProvider();
serviceProvider.GetService<StudentApp>().Start();
}
private static void ConfigureServices(IServiceCollection
serviceCollection)
{
IConfigurationRoot configuration = GetConfiguration();
Database database1 = new SqlDatabase(configuration.GetSection("Configuration:ConnectionString1").Value;
Database database2 = new SqlDatabase(configuration.GetSection("Configuration:ConnectionString2").Value;
// Here I am doing Multiple injections
serviceCollection.AddSingleton(database1);
serviceCollection.AddSingleton(database2);
serviceCollection.AddOptions();
serviceCollection.Configure<AppSettings(configuration.GetSection("Configuration"));
serviceCollection.AddSingleton(configuration);
serviceCollection.AddTransient<IStudentDataAccess,StudentDataAccess>();
serviceCollection.AddTransient<StudentApp>();
}
private static IConfigurationRoot GetConfiguration()
{
return new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true)
.Build();
}
StudentApp Class:
private readonly IStudentDataAccess _dataAccess;
private readonly AppSettings _config;
private readonly Database _database1;
private readonly Database _database2;
public StudentApp(IStudentDataAccess dataAccess,IOptions<AppSettings>
config, Database database1, Database database2)
{
_dataAccess= dataAccess;
_config = config.Value;
_database1 = database1;
_database2 = database2;
}
public void Start()
{
int count= _dataAccess.GetStudentCount(deptId);
}
DataAccess classes:
public interface IStudentDataAccess
{
int GetStudentCount(int deptId);
}
public class StudentDataAccess : IStudentDataAccess
{
private readonly AppSettings _config;
private readonly Database _database1;
private readonly Database _database2;
public StudentDataAccess (IOptions<AppSettings> config, Database
database1,Database database2)
{
_config = config.Value;
_database1 = database1;
_database2 = database2;
}
public int GetStudentCount(int deptId)
{
// Execute queries either by Database1 or 2.
}
}
Database class used is from Microsoft.Practices.EnterpriseLibrary.Data. How can I avoid creating multiple Singleton classes for different connection strings?
Any help?
IEnumerable<string> connectionStringsparameter and internally handle which connection each query should be launched against.