十二个 ASP.NET Core 例子——配置操作

  目录:

  1. 简单配置(利用configration 键值读取)
  2. 使用选项和配置对象(自定义类绑定配置文件实现读取)
  3. IOptionsSnapshot(配置文件更改时也变化)
  4. 内存数据放到配置对象中
  5. 实体框架自定义配置
  6. CommandLine配置(利用命令行配置)

     注:这是院子里面大神提供的例子。传送门


 

  1.简单配置(利用configration 键值读取)

  注意点多级节点用“:”冒号

        public static IConfigurationRoot Configuration { get; set; }//吐槽没有开放出来。每次都要new

        public HomeController()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");
            Configuration = builder.Build();
            var value = Configuration["option1"];//一级节点
            var value2 = Configuration["Logging:IncludeScopes"];//二级节点
            var value3 = Configuration["Logging:LogLevel:Default"];//三级节点
            var value4 = Configuration["Patients:1:Name"];//数据情况下,去第二个元素的第一节点
        }
View Code

  appsettings.json 文件

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-AspNetCoreAuthIdentity-c52f1669-ef35-4a6f-af80-47f83d0b7b98;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "option1": "value1_from_json",
  "option2": 2,
  "Patients": [
    {
      "Name": "Gandalf",
      "Age": "1000"
    },
    {
      "Name": "Harry",
      "Age": "17"
    }
  ]
}
View Code

    2.使用选项和配置对象(自定义类绑定配置文件实现读取)

  创建自己的类。

    public class MyOptions
    {
        public MyOptions()
        {
            // Set default value.
            Option1 = "value1_from_ctor";
        }
        public string Option1 { get; set; }
        public int Option2 { get; set; } = 5;
    }
View Code

    项目启动时注入到配置中Services.Configure

        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();

            // Register the IConfiguration instance which MyOptions binds against.
            services.Configure<MyOptions>(Configuration);
        }
View Code

  获取值

        private readonly MyOptions _options;

        public HomeController(IOptions<MyOptions> options)
        {
            _options = options.Value;
        }
View Code

 appsetting.json不用和类的字段完全一致,只要包含就可以了

  3.IOptionsSnapshot(配置文件更改时也变化)

        private readonly MyOptions _options;

        public HomeController(IOptionsSnapshot<MyOptions> options)
        {
            _options = options.Value;
        }
View Code

IOptionsSnapshot的作用:在配置文件修改的时候,配置数据也会变化。(刷新页面)

 4.内存数据放到配置对象中(AddInMemoryCollection)

        public static IConfigurationRoot Configuration { get; set; }
        public HomeController()
        {
            var dict = new Dictionary<string, string>
            {
                {"Profile:MachineName", "Rick"},
                {"App:MainWindow:Height", "11"},
                {"App:MainWindow:Width", "11"},
                {"App:MainWindow:Top", "11"},
                {"App:MainWindow:Left", "11"}
            };
            var builder = new ConfigurationBuilder();
            builder.AddInMemoryCollection(dict);
            Configuration = builder.Build();
            var vlaue = Configuration["Profile:MachineName"];
        }
View Code

顾名思义,不用去配置文件中读取,可以直接把内存中的数据放到配置对象中。【感觉有点没必要,既然在内存中,为什么不直接用】

这里还讲了一个GetValue<T>;作用:确定配置的值类型,设置默认值。用法:Configuration.GetValue<int>("App:MainWindow:Left", 80);

 5.实体框架自定义配置(AddEntityFrameworkConfig)

利用EF读取数据库读取数据和写入数据。 类似利用EF 对数据库数据操作。

1.创建实体类 2.创建DbContext 3.创建自定义配置提供程序EFConfigProvider,4.创建资源给Provider,5.AddEntityFrameworkConfig 6.读取

代码较多操作较多就不贴了。。

 6.CommandLine配置(AddCommandLine)命令行配置

先添加引用“Microsoft.Extensions.Configuration.CommandLine”

控制台类型下,添加命令行参数

        public static IConfigurationRoot Configuration { get; set; }

        public static Dictionary<string, string> GetSwitchMappings(
            IReadOnlyDictionary<string, string> configurationStrings)
        {
            return configurationStrings.Select(item =>
                    new KeyValuePair<string, string>(
                        "-" + item.Key.Substring(item.Key.LastIndexOf(':') + 1),
                        item.Key))
                .ToDictionary(
                    item => item.Key, item => item.Value);
        }
        public static void Main(string[] args = null)
        {
            var dict = new Dictionary<string, string>
            {
                {"Profile:MachineName", "Rick"},
                {"App:MainWindow:Left", "11"}
            };
            var builder = new ConfigurationBuilder();
            builder.AddInMemoryCollection(dict)
                .AddCommandLine(args, GetSwitchMappings(dict));
            Configuration = builder.Build();
            Console.WriteLine($"Hello {Configuration["Profile:MachineName"]}");

            // Set the default value to 80
            var left = Configuration.GetValue<int>("App:MainWindow:Left", 80);
            Console.WriteLine($"Left {left}");
            Console.ReadKey();
        }
View Code

注意:命令行参数有一定的格式,也可以利用GetSwitchMappings自定义格式。

posted @ 2017-05-09 10:29  TeemoHQ  阅读(2021)  评论(0编辑  收藏  举报