8_在.Net Core库类项目中读取跨项目配置文件
如在asp.net Core的appsettings.json文件里加入下面的配置
"ConnectionStrings": {
"SchoolContext": "Server=.;Database=SchoolContext;uid=sa;password=123456"
}
在Models类库里的ConfigurationHelper类里读取
namespace Models
{
public static class ConfigurationHelper
{
private static IConfiguration _config;
public static void Configure(IConfiguration config)
{
_config = config;
}
//根据配置文件键读取对应的值
public static string GetConfigValueByKey()
{
//var value = _config["ConnectionStrings:SchoolContext"];//这样获取:"ConnectionStrings:SchoolContext"
var value = _config.GetSection("ConnectionStrings")["SchoolContext"];
if (value == null)
{
return "";
}
return value;
}
}
}
在asp.netCore项目的Startup类的构造函数里进行注入
public Startup(IConfiguration configuration)
{
Configuration = configuration;
ConfigurationHelper.Configure(Configuration);
}
这样运行项目时调用类库的类里就能在类库里读取到配置文件信息。