.Net core 在類庫中獲取配置文件Appsettings中的值

    大多數狀況,咱們開發的程序中都含有不少個類庫和文件夾,有時候,咱們會遇到程序中的類庫須要獲取配置文件的信息的狀況。json

像dapper 中須要使用鏈接字符串的時候,那麼咱們一直從主程序中傳值這是個很差的方式,因此我特意百度了很久,大部分都不是很完美,app

因此今天咱們來介紹的就是一種很方便的方式了。ide

    首先咱們新建一個儲存數據的類:ui

    public class AppSetting
    {
        public string ConnectionString{ get; set; }
    }

    我這裏是獲取鏈接字符串,因此就有一個鏈接字符串的屬性。spa

    而後咱們能夠新建一個公共類,而後經過屬性注入獲取環境配置,像Development 的appsettings,再進入到appsettings.Development.json獲取數據:code

    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方法是泛型方法,因此你能夠隨意新建儲存數據的類。blog

而後就是使用它:這裏是由於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包:字符串

到這裏就很完美啦,結束。get

相關文章
相關標籤/搜索