zoukankan      html  css  js  c++  java
  • .Net core 在类库中获取配置文件Appsettings中的值

        大多数情况,我们开发的程序中都含有很多个类库和文件夹,有时候,我们会遇到程序中的类库需要获取配置文件的信息的情况。

    像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包:

    到这里就很完美啦,结束。

  • 相关阅读:
    排序算法(二)插入排序---直接插入排序
    Shazam 是如何听音辨曲的?
    Android 读取<meta-data>元素的数据
    Android <uses-featureandroid:name="string">详解
    Android AsyncTask的用法
    Android ViewPager使用详解
    Git 使用教程(4)—— Git 常用命令集合
    Git 使用教程(3)
    Git 使用教程(2)
    Git 使用教程
  • 原文地址:https://www.cnblogs.com/Ivan-Wu/p/11185770.html
Copyright © 2011-2022 走看看