大多数状况,咱们开发的程序中都含有不少个类库和文件夹,有时候,咱们会遇到程序中的类库须要获取配置文件的信息的状况。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