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);
  }
}

版权声明:
作者:congcong
链接:https://www.techfm.club/p/43651.html
来源:TechFM
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>