ASP.NET5配置

时间:2023-12-06 00:01:02

ASP.NET5支持各种各样的配置,应用程序配置数据可以来自JSON, XML或者INI格式的文件,也能来自环境变量,你也可以自定义你自己的Configuration Provider.

1. 获取和设置配置文件

简单地,Configuration类是一个源的集合,它可以提供读或写键值对,你至少配置一个源,如下例所示:

var builder = new ConfigurationBuilder();

builder.Add(new MemoryCOnfigurationSource());

var config = builder.Build();

config.Set("somekey", "somevalue");

string setting = config.Get("somekey");

string setting2 = config["somekey"];

在Json文件中,key/value是通过:来分开的, 如果有多个层次时,键值也可以有:,如 Data:DefaultConnection:ConnectionString.

2. 使用内建的提供者

框架提供内建的多种配置文件源,如JSON, XML, INI. 也可以是环境变量,如下所示:

var builder = new ConfigurationBuilder(".");

builder.AddJsonFile("appsettings.json");

builder.AddEnvironmentVariables();

var config = builder.Build();

如果一个配置键存在多个配置文件当中,以配置顺序最晚的那个为准,上面的例子,以环境变量里变量为准 ,ASP.NET组建议把环境变量做为最后一个配置。

基于环境的配置文件可以如下配置:

public Startup(IHostingEnvironment env)

{

  var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json")

    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

}

在开发环境,配置文件为:appsettings.Development.json

3. 使用Options和Configuration对象

public class MyOptions

{

  public string Option1 {get;set;}

  public int Option2 {get;set;}

}

选项可以通过IOptions<TOptions>注入到你的应用程序当中去,例如:

public class HomeController : Controller

{

  public HomeController(IOptions<MyOptions> optionsAccessor)

}

配置Options如下:

public void ConfigureServices(IServiceCollection services)

{

  services.AddOptions();

  // Configure MyOptions using config

  services.Configure<MyOptions>(Configuration);

  // Confgiure MyOptions using code

  services.Configure<MyOptions>(myOptions => { myOptions.Option1 = "value1_from_action"; });

}

MyOptions.Option1可以配置在appsettings.json文件里面

4. 自定义providers

你可以写一个类继承自ConfigurationSource, 我们用EF来读取数据库的配置。

public class ConfigurationValue

{

  public string Id{get;set;}

  public string Value{get;set;}

}

public class ConfigurationContext : DbContext

{

  public COnfigurationContext(DbConextOptions options) : base(options) {}

  public DbSet<ConfigurationValue> Values{get;set;}

}

public class EntityFrameworkConfigurationSource : ConfigurationSource

{

  public EntityFrameworkConfigurationSource(Action<DbContextOptionsBuilder> optionsAction)

  {

    OptionsAction = optionsAction;

  }

  Action<DbContextOptionsBuilder> OptionsAction {get;set;}

  public override void Load()

  {

    var builder = new DbContextOptionsBuilder<ConfigurationContext>();

    OptionsAction(builder);

    using(var dbContext = new ConfigurationContext(builder.Options))

    {

      dbContext.Database.EnsureCreated();

      Data = !dbContext.Values.Any() ? CreateAndSaveDefaultValues(dbContext)

        : dbContext.Values.ToDictionary( c=> c.Id, c=> c.Value);

    }

  }

  private IDictionary<string, string> CreateAndSaveDefaultValues(ConfigurationContext dbContext)

  {

    var configValues = new Dictionary<string, string>{...};

    dbContext.Values.AddRange(configValues.Select(kvp => new ConfigurationValue(){Id = kvp.Key, value = kvp.Value }).ToArray());

    dbContext.SaveChanges();

    return configValues;

  }

}

public static class EntityFrameworkExtensions

{

  public static IConfigurationBuilder AddEntityFramework(this IConfigurationBuilder builder, Action<DbContextOptionsBuilder> setup)

  {

    return builder.Add(new EntityFrameworkConfigurationSource(setup));

  }

}

public class Program

{

  public void Main(string[] args)

  {

    var builder = new ConfigurationBuilder(".");

    builder.AddJsonFile("appsettings.json");

    var config = builder.Build();

    builder.AddEntityFramework(options => options.UseSqlServer(config["Data:DefaultConnection:ConnectionString"]));

    config = builder.Build();

  }

}