It's pretty simple...use IOptions at the composition root like so in startup.cs or in a separate class library project:
services.AddScoped<IDbConnection, OracleConnection>();
services.AddScoped<IDbConnection, SqlConnection>();
services.Configure<DatabaseConnections>(configuration.GetSection("DatabaseConnections"));
services.AddScoped(resolver =>
{
var databaseConnections = resolver.GetService<IOptions<DatabaseConnections>>().Value;
var iDbConnections = resolver.GetServices<IDbConnection>();
databaseConnections.OracleConnections.ToList().ForEach(ora =>
{
ora.dbConnection = iDbConnections.Where(w => w.GetType() == typeof(OracleConnection)).FirstOrDefault();
ora.dbConnection.ConnectionString = ora.ConnectionString;
//ora.Guid = Guid.NewGuid();
});
databaseConnections.MSSqlConnections.ToList().ForEach(sql =>
{
sql.dbConnection = iDbConnections.Where(w => w.GetType() == typeof(SqlConnection)).FirstOrDefault();
sql.dbConnection.ConnectionString = sql.ConnectionString;
//sql.Guid = Guid.NewGuid();
});
return databaseConnections;
});
Above uses the Configuration class to map the appsettings.json section that houses your connection strings. Here's an example of the appsettings.json file:
"DatabaseConnections": {
"OracleConnections": [
{
"Alias": "TestConnection1",
"ConnectionString": "Data Source=(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP) (HOST = ) (PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = ) ) );User Id=;Password=;"
},
{
"Alias": "TestConnection2",
"ConnectionString": "Data Source=(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP) (HOST = ) (PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = ) ) );User Id=;Password=;"
}
],
"MSSqlConnections": [
{
"Alias": "Music",
"ConnectionString": "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\MusicLibrary.mdf;Integrated Security=True;Connect Timeout=30"
}
]
}
IOptions now gives me the ability to set my connection string at runtime in startup.cs close to the composition root.
Here's my class I'm using to map my connection strings:
public class DatabaseConnections : IDatabaseConnections
{
public IEnumerable<Connection> OracleConnections { get; set; }
public IEnumerable<Connection> MSSqlConnections { get; set; }
}
Now any service layer has access to multiple db connections and provider per request!
Github project: https://github.com/B-Richie/Dapper_DAL