dotnet6读取Configuration

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

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

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

你可能感兴趣的:(dotnet6读取Configuration)