.net 中使用模型读取配置文件,并使用模型绑定注入服务容器
·
一、创建Appsetings.json配置文件
{
"Logging": {
"LogLevel": {
"Default": "Information"
}
},
"DB": {
"DbType": "SqlServer",
"ConnectionString": "Server=localhost;Database=MyAppDB;User Id=myusername;Password=mypassword;"
}
}
注:要设置配置文件属性为“复制到输出目录------如果较新则复制”,否则当程序运行时修改配置文件将会不生效。
二、创建模型
internal class DbSettings
{
public string? DbType { get; set; }
public string? ConnectionString { get; set; }
}
注:模型要与json配置文件中的参数对应
三、安装nuget包
1、读取json配置文件的核心基础包
Microsoft.Extensions.Configuration.Json
2、将IConfiguration中的键值对绑定到模型的包
Microsoft.Extensions.Configuration.Binder
3、管理配置和服务的包
Microsoft.Extensions.Options
4、依赖注入的包
Microsoft.Extensions.DependencyInjection
四、创建依赖注入测试类
internal class TestSnapshot
{
private readonly IOptionsSnapshot<DbSettings> _dbSettings;
public TestSnapshot(IOptionsSnapshot<DbSettings> dbSettings)
{
_dbSettings = dbSettings;
}
public void Show()
{
Console.WriteLine($"Snapshot DbTye:{_dbSettings.Value.DbType}");
Console.WriteLine($"Snapshot ConnectionString:{_dbSettings.Value.ConnectionString}");
}
}
注:IOptionsSnapshot 的作用域为Scoped,当在同一请求或者同一作用域中时,支持配置自动刷新(需要注意的是当配置文件修改后,再次请求时才是新值)
五、在program.cs中完成JSON配置文件读取、绑定、依赖注入
static void Main(string[] args)
{
//创建json配置文件读取器
ConfigurationBuilder jsonBuilder = new ConfigurationBuilder();
//设置basePath
//jsonBuilder.SetBasePath(Directory.GetCurrentDirectory());
//读取json配置文件
jsonBuilder.AddJsonFile("appsetings.json", optional: false, reloadOnChange: true);
//读取配置文件构建IConfiguration根对象
IConfigurationRoot config = jsonBuilder.Build();
//创建服务容器
IServiceCollection serviceCollection = new ServiceCollection();
//这里要用到
//Microsoft.Extensions.Options包
//Microsoft.Extesions.Configuration.Binder
serviceCollection.AddOptions().Configure<DbSettings>(e => config.GetSection("DB").Bind(e));
//在服务中注入testSnapshot对象
serviceCollection.AddTransient<TestSnapshot>();
//构建provider服务提供器
using (ServiceProvider services = serviceCollection.BuildServiceProvider())
{
//循环获取模型中的值
while (true)
{
using (var scope = services.CreateScope())
{
var spScope = scope.ServiceProvider;
//获取TestSnapshot对象,并调用show方法,来测试通过构造器注入的 注入的DbSettings对象
TestSnapshot test = spScope.GetRequiredService<TestSnapshot>();
test.Show();
}
//提示
Console.WriteLine("可以改配置啦...");
Console.ReadKey();
}
}
}
可以运行控制台程序试一试:
Snapshot DbTye:Mysql
Snapshot ConnectionString:Server=localhost;Database=MyAppDB;User Id=myusername;Password=mypassword;
可以改配置啦...
Snapshot DbTye:Mysql
Snapshot ConnectionString:Server=localhost;Database=MyAppDB;User Id=myusername;Password=mypassword;
可以改配置啦...
至此,配置文件的读取、绑定、依赖注入就完成了。
更多推荐

所有评论(0)