1+ using System ;
2+ using System . Collections . Generic ;
3+ using System . Linq ;
4+ using Microsoft . Extensions . Configuration ;
5+ using Migrator . Tests . Settings . Interfaces ;
6+ using Migrator . Tests . Settings . Models ;
7+
8+ namespace Migrator . Tests . Settings ;
9+
10+ /// <summary>
11+ /// Reads the configuration from appsettings.
12+ /// </summary>
13+ public class ConfigurationReader ( ) : IConfigurationReader
14+ {
15+ private const string AspnetCoreVariableString = "ASPNETCORE_ENVIRONMENT" ;
16+
17+ /// <summary>
18+ /// Gets the database connection config by its ID.
19+ /// </summary>
20+ /// <param name="id">Use one of the IDs in <see cref="ConnectionIdentifiers"/></param>
21+ /// <returns></returns>
22+ public DatabaseConnectionConfig GetDatabaseConnectionConfigById ( string id )
23+ {
24+ var configurationRoot = GetConfigurationRoot ( ) ;
25+ var aspNetCoreVariable = GetAspNetCoreEnvironmentVariable ( ) ;
26+
27+ var databaseConnectionConfigs = configurationRoot . GetSection ( "DatabaseConnectionConfigs" )
28+ . Get < List < DatabaseConnectionConfig > > ( ) ?? throw new KeyNotFoundException ( ) ;
29+
30+ return databaseConnectionConfigs . Single ( x => x . Id == id ) ;
31+ }
32+
33+ /// <summary>
34+ /// Gets the configuration root. Currently it is not used for production therefore we do not use appsettings.json.
35+ /// Your personal appsettings.Development.json will be used if your ASPNETCORE_ENVIRONMENT env variable is set to "Development".
36+ /// </summary>
37+ /// <returns></returns>
38+ public IConfigurationRoot GetConfigurationRoot ( )
39+ {
40+ var aspNetCoreVariableName = GetAspNetCoreEnvironmentVariable ( ) ;
41+
42+ return new ConfigurationBuilder ( )
43+ . SetBasePath ( AppDomain . CurrentDomain . BaseDirectory )
44+ . AddJsonFile ( "appsettings.json" , optional : false , reloadOnChange : false )
45+ . AddJsonFile ( $ "appsettings.{ aspNetCoreVariableName } .json", optional : true , reloadOnChange : false )
46+ . Build ( ) ;
47+ }
48+
49+ private static string GetAspNetCoreEnvironmentVariable ( )
50+ {
51+ var aspNetCoreVariable = Environment . GetEnvironmentVariable ( AspnetCoreVariableString , EnvironmentVariableTarget . Process ) ;
52+
53+ if ( string . IsNullOrEmpty ( aspNetCoreVariable ) )
54+ {
55+ aspNetCoreVariable = Environment . GetEnvironmentVariable ( AspnetCoreVariableString , EnvironmentVariableTarget . User ) ;
56+ }
57+ else if ( string . IsNullOrEmpty ( aspNetCoreVariable ) )
58+ {
59+ aspNetCoreVariable = Environment . GetEnvironmentVariable ( AspnetCoreVariableString , EnvironmentVariableTarget . Machine ) ;
60+ }
61+
62+ if ( string . IsNullOrWhiteSpace ( aspNetCoreVariable ) )
63+ {
64+ throw new Exception ( $ "The environment variable '{ AspnetCoreVariableString } ' is not set.") ;
65+ }
66+
67+ return aspNetCoreVariable ;
68+ }
69+ }
0 commit comments