大多數情況,我們開發的程序中都含有很多個類庫和文件夾,有時候,我們會遇到程序中的類庫需要獲取配置文件的信息的情況。
像dapper 中需要使用連接字符串的時候,那么我們一直從主程序中傳值這是個不好的方式,所以我特地百度了好久,大部分都不是很完美,
所以今天我們來介紹的就是一種很方便的方式了。
首先我們新建一個儲存數據的類:
public class AppSetting { public string ConnectionString{ get; set; } }
我這里是獲取連接字符串,所以就有一個連接字符串的屬性。
然后我們可以新建一個公共類,然后通過屬性注入獲取環境配置,像Development 的appsettings,再進入到appsettings.Development.json獲取數據:
public class ConfigurationHelper { public IConfiguration config { get; set; } public ConfigurationHelper() { IHostingEnvironment env = MyServiceProvider.ServiceProvider.GetRequiredService<IHostingEnvironment>(); config = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables() .Build(); } public T GetAppSettings<T>(string key) where T : class, new() { var appconfig = new ServiceCollection() .AddOptions() .Configure<T>(config.GetSection(key)) .BuildServiceProvider() .GetService<IOptions<T>>() .Value; return appconfig; } }
這里GetAppSettings方法是泛型方法,所以你可以隨意新建儲存數據的類。
然后就是使用它:這里是因為dapper要使用連接字符串:
public class DapperHelper { public static IDbConnection GetConnection() { string connection = new ConfigurationHelper().GetAppSettings<AppSetting>("ConnectionStrings").ConnectionString;
IDbConnection conn = new MySqlConnection(connection);
conn.Open();
return conn;
}
}
其實這里還需要注意我們需要引用一些nuget包:
到這里就很完美啦,結束。