文章目录
项目下载地址 .net core 3.1 获取配置文件
项目如下
项目名 | 输出类型 | 框架 | 说明 |
---|---|---|---|
ConfigExtends | 类库 | .net core 3.1 | 获取配置文件的扩展 |
Study.Factory.Reflect | 控制台应用程序 | .net core 3.1 | 使用获取配置文件 |
ConfigExtends
IConfigHandle
using System;
using System.Text;
using System.Collections.Generic;
namespace ConfigExtends
{
interface IConfigHandle
{
string GetConfig(string key);
}
}
ConfigService
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
namespace ConfigExtends
{
public class ConfigHandle : IConfigHandle
{
private readonly IConfiguration _configuration;
public ConfigHandle(IConfiguration configuration) => _configuration = configuration;
public string GetConfig(string key)
{
return _configuration.GetSection(key).Value;
}
}
}
ConfigHandle
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ConfigExtends
{
public class ConfigService
{
public static IHostBuilder _HostBuilder
{
get
{
var builder = new HostBuilder()
.ConfigureAppConfiguration((hostcontext, configApp) =>
{
//指定需要读取的文件,文件属性记得设置为始终复制
configApp.AddJsonFile("appsettings.json");
})
.ConfigureServices((hostcontext, services) =>
{
services.AddTransient<IConfigHandle, ConfigHandle>();
})
.UseConsoleLifetime();
return builder;
}
}
public static string GetConfig(string key)
{
var builder = _HostBuilder.Build();
using var serviceScope = builder.Services.CreateScope();
var config = serviceScope.ServiceProvider.GetService<IConfigHandle>();
return config.GetConfig(key);
}
}
}
Study.Factory.Reflect
appsettings.json
{
"exclude": [
"**/bin",
"**/bower_components",
"**/jspm_packages",
"**/node_modules",
"**/obj",
"**/platforms"
],
"ConnectionStrings": {
"defulat": "server=.;database=Reflect;uid=sa;pwd=1"
}
}
Program.cs
Console.WriteLine(ConfigService.GetConfig("ConnectionStrings:defulat"));