dotnet6读取Configuration
- 读取ConnectionStrings
- 读取嵌套结构配置 Student示例
- 非注入方式读取配置(使用Static属性)
appsettings.json
{
"ConnectionStrings": {
"mongodb": "mongodb://user:[email protected]:28001,demo.mongo:28002/?slaveOk=true",
"mongodb-ext": "mongodb://user:[email protected]:28001,demo.mongo:28002/?slaveOk=true"
},
"Student": {
"ID": "1",
"Name": "tom"
},
"Foo": "bar"
}
var builder = WebApplication.CreateBuilder(args);
// connection string
var connectionString = builder.Configuration.GetConnectionString("mongodb");
// config
var id = builder.Configuration["Student:ID"];
var student = builder.Configuration.GetSection("Student").Get();
// 初始化,以便后续非注入方式读取配置
MySettings.Instance = builder.Configuration.Get();
// mongo配置注册
builder.Services.Configure(options =>
{
options.ConnectionString = builder.Configuration.GetConnectionString("mongodb");
options.DbName = "demo";
});
// mongo配置注册
builder.Services.Configure(options =>
{
options.ConnectionString = builder.Configuration.GetConnectionString("mongodb-ext");
options.DbName = "demoExt";
});
// 配置
public class Student
{
public string ID { get; set; }
public string Name { get; set; }
}
// 非注入方式读取配置
public class MySettings
{
public static MySettings Instance { get; set; }
public string Foo { get; set; }
}
// mongo配置
public class MongoSessionOption
{
public string ConnectionString { get; set; }
public string DbName { get; set; }
}
// mongo配置
public class MongoSessionOptionExt
{
public string ConnectionString { get; set; }
public string DbName { get; set; }
}
public class DemoMongoRepo
{
private readonly MongoSessionOption mongoSessionOption;
// 构造函数注入mongo配置
public DemoMongoRepo(IOptions options)
{
mongoSessionOption = options.Value;
}
}
public class StudentService
{
pubic void Test()
{
// 非注入方式读取配置
Console.WriteLine(MySettings.Instance.Foo);
}
}
共有 0 条评论